2016-11-26 81 views
6

我试图把这个:字符串分割为n个字的数组

"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个字的字符串。)

+0

分割字符串的规则是什么? –

+0

@ A.J我更新了这个问题。 – alex

+3

'.split()'不包括分隔符它确实是这样的,你想的正好相反。你需要做一个常规的正则表达式搜索(用'g'修饰符)而不是分割。 – JJJ

回答

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);

Regex explanation here.

4

你的代码是好去。但不是分裂。拆分会将其视为分隔符。 例如是这样的:

var arr = "1, 1, 1, 1"; 
arr.split(',') === [1, 1, 1, 1] ; 
//but 
arr.split(1) === [', ', ', ', ', ', ', ']; 

而是使用matchexec。这样

var x = "This is a test this is a test"; 
 
var re = /\b[\w']+(?:[^\w\n]+[\w']+){0,2}\b/g 
 
var y = x.match(re); 
 
console.log(y);

2

作为一种替代方法,可以通过空间和在批量合并块分割字符串。

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))

0

使用空格特殊字符(\s)和match函数,而不是split

var wordList = sample.text().match(/\s?(?:\w+\s?){1,3}/g); 

split将字符串中的正则表达式匹配。匹配返回匹配的任何内容。

检查此fiddle

2

你可能分裂这样的:

var str = 'This is a test this is a test'; 
 
var wrd = str.split(/((?:\w+\s+){1,3})/); 
 
console.log(wrd);

但是,你必须从阵列中删除空元素。