4

我有一个不寻常的要求。给定如下字符串:

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

我需要每五个单词插入一个“\n”。字符串 a 可以包含任意数量的字母数字字符。

有人可以给我一个想法,我该怎么做?

4

4 回答 4

11
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
*/
于 2012-06-10T12:32:09.847 回答
4

想法首先出现在我的脑海中

    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);
于 2012-06-10T12:28:23.687 回答
2

您可以将字符串拆分为几个单词并将它们连接在一起,同时每 5 个单词添加一个“\n”:

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

请注意 html 代码中的“\n”(例如在“div”或“p”标签中)对网站的访问者是不可见的。在这种情况下,您需要使用“<br/>”

于 2012-06-10T12:30:51.363 回答
1

尝试:

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);
于 2012-06-10T12:29:26.463 回答