Are the lines split in javascript?

I use the my_colors.split ("") method, but I want to split or split a line in a fixed number of words, for example, each spread occurs after 10 words or so ... how to do this in javascript?

+4
source share
4 answers

Try this: this regular expression captures groups of ten words (or less for the last words):

var groups = s.match(/(\S+\s*){1,10}/g); 
+7
source

You can use a regular expression, for example /\S+/g , to split a line if the words are separated by multiple spaces or any other spaces.

I'm not sure my example below is the most elegant way to do this, but it works.

 <html> <head> <script type="text/javascript"> var str = "one two three four five six seven eight nine ten " + "eleven twelve thirteen fourteen fifteen sixteen " + "seventeen eighteen nineteen twenty twenty-one"; var words = str.match(/\S+/g); var arr = []; var temp = []; for(var i=0;i<words.length;i++) { temp.push(words[i]); if (i % 10 == 9) { arr.push(temp.join(" ")); temp = []; } } if (temp.length) { arr.push(temp.join(" ")); } // Now you have an array of strings with 10 words (max) in them alert(" - "+ arr.join("\n - ")); </script> </head> <body> </body> </html> 
+3
source

You can split ("), then combine (" ") the resulting array 10 elements at a time.

+2
source

You can try something like

 console.log("word1 word2 word3 word4 word5 word6" .replace(/((?:[^ ]+\s+){2})/g, '$1{special sequence}') .split(/\s*{special sequence}\s*/)); //prints ["word1 word2", "word3 word4", "word5 word6"] 

But you better do either split(" ") and then join(" ") or write a simple tokenizer yourself, which will split this line in any way.

0
source

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


All Articles