我试图改变这个:
"This is a test this is a test"
进入这个:
["This is a","test this is","a test"]
我试过这个:
const re = /\b[\w']+(?:[^\w\n]+[\w']+){0,2}\b/ const wordList = sample.split(re) console.log(wordList)
但我得到了这个:
[ '',' ',' ']
为什么是这样?
(规则是每N个字分割字符串.)
解决方法
String#split
方法将按匹配的内容拆分字符串,因此它不会在结果数组中包含匹配的字符串.
使用String#match
方法在正则表达式上使用全局标记(g):
var sample="This is a test this is a test" const re = /\b[\w']+(?:\s+[\w']+){0,2}/g; const wordList = sample.match(re); console.log(wordList);