I have an unusual request. Given a string 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 a "\n" every fifth word. The string a can have any number of alphanumeric characters.
Can someone give me an idea how I could do this?
I have an unusual request. Given a string 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 a "\n" every fifth word. The string a can have any number of alphanumeric characters.
Can someone give me an idea how I could do this?
Share Improve this question asked Jun 10, 2012 at 12:18 Alan2Alan2 24.6k86 gold badges275 silver badges478 bronze badges 1- stackoverflow.com/questions/4168644/… – Jared Farrish Commented Jun 10, 2012 at 12:28
4 Answers
Reset to default 14a.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
*/
Idea first came to my mind
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);
You could split the string into several words and join them together while adding a "\n" every 5th 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 consider that "\n" in html-code (for example in a "div" or "p" tag) will not be visible to the visitor of a website. In this case you would need to use "<br/>"
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);