Splitting a string into an array of n words

I am trying to do this:

"This is a test this is a test" 

in it:

 ["This is a", "test this is", "a test"] 

I tried this:

 const re = /\b[\w']+(?:[^\w\n]+[\w']+){0,2}\b/ const wordList = sample.split(re) console.log(wordList) 

But I got this:

 [ '', ' ', ' '] 

Why is this?

(The rule is to break the line into each N words.)

+6
source share
5 answers

The String#split method String#split string into consistent content so that it does not include the consistent string in the result array.

Use the String#match method with a global flag ( g ) instead:

 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.

+9
source

your code is good. but not with a split. split will consider it as a limiter. for example, something like this:

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

Use match or exec instead. like this

 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); 
+4
source

As an alternative approach, you can split the string by space and merge the pieces in batch mode.

 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)) 
+2
source

You can break it up like this:

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

But you need to remove the empty elements from the array.

+2
source

Use the special character of the special type ( \s ) and match instead of split :

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

Separates the line where the regular expression occurs. Match returns everything that matches.

Check the fiddle .

0
source

Source: https://habr.com/ru/post/1012672/


All Articles