typescript - 使用带有 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()
方法,以便使用正则表达式作为拆分分隔符将全名分隔为字符串数组中的元素
有谁知道正则表达式是什么?我可以让逗号工作,但我似乎无法弄清楚如何让多个标点符号和特定短语一起工作
解决方案
两个建议:
只需计算和的数量
,
并and
添加一个。,
按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);
推荐阅读
- java - 如何在android studio中计算卫星的仰角、LNB偏斜和方位角值?
- android - 调节 Android AudioTrack 播放速度
- angular - 关键依赖:require函数的使用方式不能静态提取依赖
- python - 更改 DataFrame 行子集的列
- ios - 在 iOS Metal 中使用 OpenCV 旋转和平移绘制 AR 立方体
- css - 悬停时图像闪烁 - css动画
- ruby - 如何在 ruby 中引发多个异常
- r - 分词加速 n R
- redis - cas redis 票务登记处
- mysql - 如何在另一个查询中传递使用 group_concat(distinct) 的查询获得的结果?