将字符串拆分为n个单词的数组

ale*_*lex 6 javascript regex

我试图改变这个:

"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个字分割字符串.)

Pra*_*lan 9

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)

正则表达式在这里解释.


Raj*_*esh 6

作为替代方法,您可以按空间拆分字符串并批量合并块。

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)