Skip to content Skip to sidebar Skip to footer

How Can I Break Up A Javascript String With A New Line Every Five Words?

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' e

Solution 1:

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
*/

Solution 2:

You could split the string into several words and join them together while adding a "\n" every 5th word:

functioninsertLines (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 thisvar 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/>"

Solution 3:

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

Post a Comment for "How Can I Break Up A Javascript String With A New Line Every Five Words?"