最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How can I break up a javascript string with a new line every five words? - Stack Overflow

programmeradmin0浏览0评论

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
Add a comment  | 

4 Answers 4

Reset to default 14
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
*/

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);
发布评论

评论列表(0)

  1. 暂无评论