代码之家  ›  专栏  ›  技术社区  ›  Joseph

在Javascript中检索一些文本

  •  0
  • Joseph  · 技术社区  · 12 月前

    我想使用现代JavaScript语法检索一个人的名字和姓氏的第一个字母。目前,我能够正确检索名字的第一个字母和姓氏的第一个字符。

    我的问题是,如果没有“of”这个词,我就无法检索它。

    这是我的Jsfidle链接----> CLICK HERE

    代码:

    /* const name = "Joshua Jones of USA"; */
    const name = "William Sanders";
    /* const name = "Grey Charles"; */
    
    function getUserInitials(name) {
      return /^(.).+([A-Z])\w+\sof\s.+$/.exec(name).slice(1, 3).join('');
    }
    
    
    console.log(getUserInitials(name));
    2 回复  |  直到 12 月前
        1
  •  2
  •   connexo    12 月前

    不确定您到底想做什么,但这解决了所示的测试用例:

    const names = ["Joshua Jones of USA", "William Sanders", "Grey Charles"];
    
    function getUserInitials(name) {
      return name.split(' ').map(w => w.charAt(0).toUpperCase()).splice(0,2);
    }
    
    for (const name of names)
      console.log(getUserInitials(name));

    如果这不能满足您的要求,请详细说明。

        2
  •  0
  •   Invulner    12 月前

    如果您的测试用例涵盖了所有可能的格式,您可以改进您的regexp:

    function getUserInitials(name) {
        const matches = /^(.).*?\s+(.).*$/.exec(name);
        if (matches) {
            return matches.slice(1, 3).join('').toUpperCase();
        } else {
            return '';
        }
    }
    
    console.log(getUserInitials("Joshua Jones of USA"));
    console.log(getUserInitials("William Sanders"));
    console.log(getUserInitials("Grey Charles"));

    或者可以先按“of”分割,然后按空格分割:

    function getUserInitials(name) {
        const [firstName, lastName] = name.split('of')[0].trim().split(' ');
    
        return `${firstName[0]}${lastName[0]}`.toUpperCase();
    }
    
    console.log(getUserInitials("Joshua Jones of USA"));
    console.log(getUserInitials("William Sanders"));
    console.log(getUserInitials("Grey Charles"));