用逗号分隔字符串到新行

时间:2013-03-13 02:18:16

标签: javascript 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

我想基本上将这个长字符串拆分为逗号并插入一个新行,使其成为

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

我该怎么做?

7 个答案:

答案 0 :(得分:22)

使用内置的splitjoin方法

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

如果您希望换行符是HTML换行符

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

这对我来说最有意义,因为你将它分成行然后用换行符加入它们。

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

使用str.split(",").join("\n")似乎(在chrome中)比str.replace(/,/g, '\n');快。

答案 1 :(得分:3)

您也可以替换它们:

string.replace(/,/g, '\n');

答案 2 :(得分: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"

答案 3 :(得分: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"

答案 4 :(得分: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);

答案 5 :(得分:0)

equals

答案 6 :(得分: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.