4

珍しいリクエストがあります。次のような文字列が与えられます:

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

5語ごとに「\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」タグ)は、Webサイトの訪問者には表示されないことに注意してください。この場合、「<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 に答える