Jump to content

Splitting Full Names


esmith

Recommended Posts

If I have data with full names (assuming they are all in "first last" format) what would be the regex expression I would need in a split function to split on last space? I want to be able to capture the first names with spaces (assuming last names never have spaces).

 

Yeah, I know there will likely be exceptions, but I'm ignoring those for now. :eek:

Link to comment
Share on other sites

If I have data with full names (assuming they are all in "first last" format) what would be the regex expression I would need in a split function to split on last space? I want to be able to capture the first names with spaces (assuming last names never have spaces).

You can use regular expressions, but dealing with array functions like join and split is generally simpler. I'll include examples of both.

Yeah, I know there will likely be exceptions, but I'm ignoring those for now. :eek:

I would actually split on the first space, which I think will be correct in more "exception" cases ("Werner von Braun", etc.). These will do that:

// First name
return name.split(' ')[0];
// OR
return name.replace(/\s.*/, '');

// Last name
return name.split(' ').slice(1).join(' ');
// OR
return name.replace(/\S*\s/, '');

If you really want to split on the last space, these will work:

// First name
return name.split(' ').slice(0, name.split(' ').length-1).join(' ');
// OR
return name.replace(/\s\S*$/, '');

// Last name
return name.split(' ').pop();
// OR
return name.replace(/.*\s/, '');

In almost every case, the array strategy is simpler than using Regular Expressions.

 

Also, note that some of these might not work if there are no spaces at all in the name.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...