【发布时间】:2021-10-19 22:17:53
【问题描述】:
我试图从字符串中删除逗号后除第一个字母之外的所有字符。该字符串基本上是姓氏,名字。
例如:
Smith,John
我尝试如下,但它删除了逗号和逗号后的所有内容。
let str = "Smith,John";
str = str.replace(/\s/g, ""); // to remove all whitespace if there is any at the beginning, in the middle and at the end
str = str.split(',')[0];
预期输出:Smith,J
谢谢!
【问题讨论】:
-
不确定您是否需要正则表达式本身,但另一种方式可能是
str.substr(0, str.indexOf(",")+2)
标签: javascript regex typescript