我试图改变这个:
"This is a test this is a test"
Run Code Online (Sandbox Code Playgroud)
进入这个:
["This is a", "test this is", "a test"]
Run Code Online (Sandbox Code Playgroud)
我试过这个:
const re = /\b[\w']+(?:[^\w\n]+[\w']+){0,2}\b/
const wordList = sample.split(re)
console.log(wordList)
Run Code Online (Sandbox Code Playgroud)
但我得到了这个:
[ '',
' ',
' ']
Run Code Online (Sandbox Code Playgroud)
为什么是这样?
(规则是每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);
Run Code Online (Sandbox Code Playgroud)
作为替代方法,您可以按空间拆分字符串并批量合并块。
function splitByWordCount(str, count) {
var arr = str.split(' ')
var r = [];
while (arr.length) {
r.push(arr.splice(0, count).join(' '))
}
return r;
}
var a = "This is a test this is a test";
console.log(splitByWordCount(a, 3))
console.log(splitByWordCount(a, 2))
Run Code Online (Sandbox Code Playgroud)