字符串操作,删除标记

时间:2011-06-03 09:31:01

标签: javascript string

我有以下循环,它会生成一小段html:

for (var i = 0; i < 5; i++) {
    test_html += 'some text here<hr />';
}

这将创建html

some text here<hr />
some text here<hr />
some text here<hr />
some text here<hr />
some text here<hr />

如何停止添加上一个<hr />,或如何删除最后一个<hr />

8 个答案:

答案 0 :(得分:7)

我只是使用一个数组。

var test_html = [];
for (var i = 0; i < 5; i++) {
    test_html.push('some text here');
}
console.log(test_html.join('<hr />'))

此外,如果您只想加入字符串,只需少一个

var test_html = '';
for (var i = 0; i < 4; i++) { //4 not 5
    test_html += 'some text here<hr />';
}
test_html += 'some text here';

答案 1 :(得分:2)

加入数组的速度要快得多,尤其是在IE中:

test_html = [];
for (var i = 0; i < 5; i++) {
    test_html.push('some text here');
}
test_html = test_html.join('<hr />');

答案 2 :(得分:0)

这样的东西?

for (var i = 0; i < 5; i++) {
    test_html += (i === 4) ? 'some text here' : 'some text here <hr />';
}

答案 3 :(得分:0)

test_html = 'some text here';
for (var i = 1; i < 5; i++) {
    test_html += '<hr />some text here';
}

如果我对数组执行此操作,则使用Array.join()

答案 4 :(得分:0)

for (var i = 0; i < 5; i++) {
    test_html += 'some text here';
    if (i < 4)
        test_html += '<hr />';
}

答案 5 :(得分:0)

for (var i = O; i < 5 ; i++) {
    test_html += 'some text here';
    if (i != 4)
        test_html += '<hr />';
}

答案 6 :(得分:0)

var loops = 5;
for (var i = 0; i < loops ; i++) {
 if (i == loops -1)
  {
    test_html += 'some text here';
  }
   else
  {
        test_html += 'some text here<hr />';
  }
}

答案 7 :(得分:0)

你应该试试这个:

for (var i = 0; i < 5; i++)
    test_html += 'some text here';
    if (i < 4) test_html += '<hr />';
}

它会创建:

some text here<hr />
some text here<hr />
some text here<hr />
some text here<hr />
some text here
相关问题