Split full name into first name and last name using Code by Zapier

  • 26 January 2022
  • 6 replies
  • 1344 views
Split full name into first name and last name using Code by Zapier
Userlevel 7
Badge +14

Ever wanted to split a full name into first name and last name?

JavaScript code to the rescue!

Now you can predictably map the output variables in your Zap steps.

 

NOTE: This will not work 100% due to the following potential conditions…

  1. Multiple First Names
  2. Multiple Last Names
  3. Middle Name(s)
  4. Name Prefix (e.g. Dr.)
  5. Name Suffix (e.g. Jr.)

 

How to Configure

 

Copy the Code

let NameFull = inputData.NameFull.trim().split(' '); // removes whitespace and splits by spaces
let NameFirst = NameFull[0]; // takes first array item
let NameLast = NameFull[NameFull.length - 1]; // takes last array item

output = [{NameFirst, NameLast, NameFull}];

 

The Results

 


6 replies

Userlevel 7
Badge +14

@nicksimard Here you go!

Hi Troy,

Can this code be modified so that I can also get the middle name as a result?

Thanks

Uwe

Userlevel 7
Badge +14

Hi @piquano 

Good question.

Splitting full names can be tricky as noted.

What if there is no middle name?

 

 

NOTE: This will not work 100% due to the following potential conditions…

  1. Multiple First Names
  2. Multiple Last Names
  3. Middle Name(s)
  4. Name Prefix (e.g. Dr.)
  5. Name Suffix (e.g. Jr.)

Hello 

This tutorial is great !! 

I m still struggling with my case  : the line doesn’t stop there, I have more words after the lastname…

theses annoying words are always the same ones, 

is there a way to get rid of them ?

 

  • Otherwise if you know how to convert your code into python and give it to me then I would be able to do this by myself.

thank you so much for your help already

Userlevel 7
Badge +14

Hi @Ak-tester 

Try asking ChatGPT by OpenAI for help writing the Python code: https://chat.openai.com/

 

 

Userlevel 1

Hi Troy,

Can this code be modified so that I can also get the middle name as a result?

Thanks

Uwe

Hey @piquano,

You can use this Python code for the first_name middle_name and last_name. It will consider the first word as the first_name, the last word as the last_name, and all the words in between, if any, will be considered as the middle_name.

For example: Olivia Grace Anderson Smith
first_name = 'Olivia'
middle_name = 'Grace Anderson'
last_name = 'Smith'

name = input_data.get('name', '').strip()
output = dict()

name_parts = name.split()
first_name = name_parts[0] if name_parts else ""
middle_name = "" if len(name_parts) <= 2 else " ".join(name_parts[1:-1])
last_name = name_parts[-1] if len(name_parts) > 1 else ""

output["first_name"] = first_name
output["middle_name"] = middle_name
output["last_name"] = last_name

print(output)

 

Reply