我试图从我的字符串中拆分出所有单词,而不在其中获得额外的空值。我目前的尝试是这样的。
var words = "This is a test!";
var arr = words.split(/\W+/);
print(arr);
输出是 This, is, a, test,
我期待的是 This, is, a, test
。这显然是由于!在我的字符串的末尾。
我希望能够插入像 This is a test
和 This is a test!
这样的字符串到我的方法中,但我想要相同的响应This, is, a, test
来自这两个字符串。
提前致谢!
最佳答案
在您的情况下,您应该使用带有 g
标志的 .match()
而不是 .split()
。
var words = "This is a test!";
var arr = words.match(/\w+/g);
console.log(arr);
关于javascript - 从字符串中提取每个单词而不在末尾获得额外的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57257561/