How to define segments when splitting a string of 2+ words using code

  • 12 July 2019
  • 2 replies
  • 4019 views

Userlevel 7
Badge +12

For example:

Someone uses their full name in one field instead of first and last in separate fields. If you then want to split it and define the first word (name) as the first name and any other words in that field as the last name, you can do that using some JavaScript code.

Option 1

First name’s the same no matter what, so we can define it here

var firstname = nameArr[0]

var lastname

Check if there’s more than 2 elements in the array (i.e. a middle or multi-stage name)

if(nameArr.length > 2){

Remove the first item in the array

nameArr.shift()

Then join that modified array up with a space in between the elements

lastname = nameArr.join(" ")

} else {

But if there’s less than two (i.e normal name) then return the last name as you were

lastname = nameArr[nameArr.length - 1]

}

output = [{firstname, lastname}];

Option 2

Here is another alternative:

var fullName = input.name.split(' ');

var firstName = fullName.shift();

var lastName = fullName.join(' ');

output = [{firstname: firstName, lastname: lastName}];

Anyone have any other creative ways of getting the same result?



This post has been closed for comments. Please create a new post if you need help or have a question about this topic.

2 replies

Userlevel 1

I'm biased towards Python, so here's the Python code step: 😁

full_name = input_data["name"].split(" ")

first_name = full_name[0]

last_name = " ".join(full_name[1:]

output = {"first_name": first_name, "last_name": last_name}

Works for mononymous name too 😎


Userlevel 4
Badge +4

I use this a lot to ignore the middle values. It controls for no data being passed and if only a first name is given you end up with the first name in both fields.

var name = inputData.name ? inputData.namesplit(' ') : '',

length = inputData.name.length;

obj = {

firstName : '',

lastName : '',

};

if(length > 0){

obj.firstName = name[0];

obj.lastName = name[length-1];

}

return obj;