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.
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