首页 > 解决方案 > 使用带有 split() 的正则表达式只是为了在字符串中获取全名

问题描述

我有这个字符串:

var author = "Tom Smith, Will Hughes, Adonis Young and Tyrek Hill";

这是函数 getNumOfAuthor :

function getNumOfAuthor(m_name:string) {
    const regex = /\s*(?:,|$)\s*/;
    var str = m_name.split(regex);
    alert(str.length);
    alert(str);
    if (str.length == 1) {
      num_of_author = 1;
    }
    else if (str.length > 1) {
      num_of_author = str.length;
    }

    return num_of_author;
  }

我想使用该split()方法,以便使用正则表达式作为拆分分隔符将全名分隔为字符串数组中的元素

有谁知道正则表达式是什么?我可以让逗号工作,但我似乎无法弄清楚如何让多个标点符号和特定短语一起工作

标签: typescript

解决方案


两个建议:

  1. 只需计算和的数量,and添加一个。

  2. ,按and分割and并计算数组的长度。

var author = "Tom Smith, Will Hughes, Adonis Young and Tyrek Hill"

// First suggestion.
let authorCount = author.match(/(, )|( and )/).length + 1;
console.log("num of authors", authorCount);

// Second suggestion.
let authors = author.split(/, | and /)
console.log(authors, authors.length);


推荐阅读