How can I break a javascript line with a new line every five words?

I have an unusual request. For a line like the following:

var a = "This is a sentance that has many words. I would like to split this to a few lines" 

I need to insert "\ n" every fifth word. String a may contain any number of alphanumeric characters.

Can someone give me an idea how I can do this?

+4
source share
4 answers
 a.split(/((?:\w+ ){5})/g).filter(Boolean).join("\n"); /* This is a sentance that has many words. I would like to split this to a few lines */ 
+7
source

An idea occurred to me

  var a = "This is a sentance that has many words. I would like to split this to a few lines"; a=a.split(" ");var str=''; for(var i=0;i<a.length;i++) { if((i+1)%5==0)str+='\n'; str+=" "+a[i];} alert(str); 
+4
source

You can split the string into several words and combine them together by adding "\ n" every fifth word:

 function insertLines (a) { var a_split = a.split(" "); var res = ""; for(var i = 0; i < a_split.length; i++) { res += a_split[i] + " "; if ((i+1) % 5 === 0) res += "\n"; } return res; } //call it like this var new_txt = insertLines("This is a sentance that has many words. I would like to split this to a few lines"); 

Please note that the "\ n" in the html code (for example, in the tag "div" or "p") will not be displayed to the website visitor. In this case, you will need to use "
"

+2
source

Try:

 var a = "This is a sentance that has many words. I would like to split this to a few lines" var b=""; var c=0; for(var i=0;i<a.length;i++) { b+=a[i]; if(a[i]==" ") { c++; if(c==5) { b+="\n"; c=0; } } } alert(b); 
+1
source

All Articles