7

我有一个字符串

This is great day, tomorrow is a better day, the day after is a better day, the day after the day after that is the greatest day

我想基本上用逗号分割这个长字符串并插入一个新行,这样它就变成了

This is great day
tomorrow is a better day
the day after is a better day
the day after the day after that is the greatest day

我怎样才能做到这一点 ?

4

7 回答 7

32

使用内置的splitjoin方法

var formattedString = yourString.split(",").join("\n")

如果您希望换行符是 HTML 换行符,那将是

var formattedString = yourString.split(",").join("<br />")

这对我来说最有意义,因为您将它分成几行,然后将它们与换行符连接起来。

虽然我认为在大多数情况下速度不如可读性重要,但在这种情况下我很好奇,所以我写了一个快速的基准测试

似乎(在 chrome 中) usingstr.split(",").join("\n")str.replace(/,/g, '\n');.

于 2013-03-13T02:20:03.513 回答
4

你也可以替换它们:

string.replace(/,/g, '\n');
于 2013-03-13T02:21:26.170 回答
1
<p id="errorMessage">Click | the |button |to |display| the| array| values| 
after| the| split.</p>

$(document).ready(function () {
var str = $("#errorMessage").text();
document.getElementById("errorMessage").innerHTML=str.split("|").join(" 
</br>"); }
于 2018-04-12T20:27:02.077 回答
0
> a = 'This is great day, tomorrow is a better day, the day after is a better day, the day after the day after that is the greatest day'
> b = a.split(', ').join('\n')

"This is great day
tomorrow is a better day
the day after is a better day
the day after the day after that is the greatest day"
于 2013-03-13T02:21:54.573 回答
0

您可以使用.split()创建字符串的所有部分的数组...

var str = 'This is great day, tomorrow is a better day, the day after is a better day, the day after the day after that is the greatest day';

str.split(',');
  -> ["This is great day", " tomorrow is a better day", " the day after is a better day", " the day after the day after that is the greatest day"]

现在,你可以对不同的部分做任何你想做的事情。既然你想加入一条新线路,你可以用.join()它把它重新组合在一起......

str.split(',').join('\n');
  -> "This is great day
      tomorrow is a better day
      the day after is a better day
      the day after the day after that is the greatest day"
于 2013-03-13T02:22:20.377 回答
0

未经我的浏览器测试尝试:

var MyStr="This is great day, tomorrow is a better day, the day after is a better day, the day after the day after that is the greatest day";
Var splitedStr = MyStr.split(",");

var returnStr = '';
for (var i = 0; i < splitedStr.length; i++)
{
    returnStr += splitedStr[i] + '<br />';
}

document.write(returnStr);
于 2013-03-13T02:23:51.367 回答
0
TermsAndConditions = "Right to make changes to the agreement.,Copyright and intellectual property.,Governing law.,Warrantaay disclaimer.,Limitation of liability."
const TAndCList = this.invoiceTermsAndConditions.split(",").join("\n \n• ");

输出 :

• Right to make changes to the agreement.
• Copyright and intellectual property.
• Governing law.
• Warrantaay disclaimer.
• Limitation of liability.
于 2021-08-04T07:12:29.443 回答