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.
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.
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"] .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With