Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Apps Script Regular Expression to get the last name of a person

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.

like image 390
user1682683 Avatar asked Jul 10 '13 14:07

user1682683


People also ask

How do I use RegEx in Google Apps Script?

Basically in above code we have a string in Line 2 for which we have to define a RegEx and finally match it. In 3rd line we have define the RegEx where [a-z]+ is to matches a characters, \\s is for space. And finally we in line 4th we executed the pattern matching with the string via RegEx.

How do you split text in Google Apps Script?

var array1 = [{}]; var string1 = "A, B, C, D"; array1 = string1. split(","); The problem is based on this kind of coding for example in flash. The string1 will split all "," then transfers it to the array1 in this format ["A","B","C", "D"] .

How do you search a regular expression on Google?

Google Search Console has introduced the use of regular expression to filter results in the performance report. Using the custom filter option at the top of the performance report, you can apply a filter with regex using the Custom (regex) dropdown option.

How do you concatenate in Appscript?

To concatenate two strings (i.e., to join them together), use the concatenation operator ( + ). Both the concatenation operator and the addition operator have the same symbol + but Apps Script will figure out which operation to perform based on the values being operated on.


1 Answers

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
like image 168
acdcjunior Avatar answered Oct 12 '22 23:10

acdcjunior