[英]How to split a string on non-alphabetic characters. Regex JavaScript
I have a sentence that I want to split into an array of words, but if there is punctuation included I end up with quotes in my array somehow. 我有一个句子,希望将其拆分为单词数组,但是如果包含标点符号,我最终会以某种方式在数组中加上引号。
console.log("This is an example sentence! Dangit".split(/[\\W/]/)); // Outputs: ["This", "is", "an", "example", "sentence", "", "Dangit"]
How do I fix this? 我该如何解决?
您可以改用match
并寻找文字字符。
console.log("This is an example sentence! Dangit".match(/\\w+/g))
Try [\\W]+
instead, which will combine multiple non-word chars together - 尝试使用
[\\W]+
,它将多个非单词字符组合在一起-
"This is an example sentence! Dangit".split(/[\W/]+/)
Array(6) [ "This", "is", "an", "example", "sentence", "Dangit" ]
单个和多个目标空间和标点符号:
[\s.?!,]+
console.log("This is an example sentence! Dangit".split(/[\\s.?!,]+/));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.