15

I am trying to write a regex to get the last name of a person.

var name = "My Name";
var regExp = new RegExp("\s[a-z]||[A-Z]*");
var lastName =  regExp(name); 
Logger.log(lastName);

If I understand correctly \s should find the white space between My and Name, [a-z]||[A-Z] would get the next letter, then * would get the rest. I would appreciate a tip if anyone could help out.

acdcjunior
  • 132,397
  • 37
  • 331
  • 304
user1682683
  • 273
  • 2
  • 6
  • 13

1 Answers1

33

You can use the following regex:

var name = "John Smith";
var regExp = new RegExp("(?:\\s)([a-z]+)", "gi"); // "i" is for case insensitive
var lastName = regExp.exec(name)[1];
Logger.log(lastName); // Smith

But, from your requirements, it is simpler to just use .split():

var name = "John Smith";
var lastName = name.split(" ")[1];
Logger.log(lastName); // Smith

Or .substring() (useful if there are more than one "last names"):

var name = "John Smith Smith";
var lastName = name.substring(name.indexOf(" ")+1, name.length); 
Logger.log(lastName); // Smith Smith
acdcjunior
  • 132,397
  • 37
  • 331
  • 304
  • Thanks for the alternatives. Very helpful. Just a quick question about the regex. If I understand it right: () brackets mean evaluate this first ?: means don't record into the regex \s is white space What is the purpose of the extra "\" ? – user1682683 Jul 10 '13 at 15:25
  • 4
    The `()` in `([a-z]+)` is actually for [grouping](http://www.regular-expressions.info/brackets.html). It allows us to use that matched part again later. `(?:)` (the `()` are mandatory here) means the opposite, do not include this group, thus just use the `()` as regular `()`, useful for applying operators to multiple expressions (like in `(\s\w)+`, `(\s\w)` would be a group. In `(?:\s\w)+` it is not.). The extra `\ `is necessary because your regex was declared using the `RegExp` constructor, and it gets a string as parameter. Thus the need for escaping `\ `as `\\ `. Let me know if it is clear! – acdcjunior Jul 10 '13 at 16:21