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

后端 未结 1 1193
别那么骄傲
别那么骄傲 2021-02-08 20:29

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         


        
相关标签:
1条回答
  • 2021-02-08 21:17

    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
    
    0 讨论(0)
提交回复
热议问题