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