Split string with commas to new line

2020-05-24 20:48发布

I have a string like

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

I wanted to basically split this one long string at the commas and insert a new line so it becomes

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

How can I do that ?

6条回答
The star\"
2楼-- · 2020-05-24 20:59

Without testing on my browser try:

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);
查看更多
Summer. ? 凉城
3楼-- · 2020-05-24 21:00

With the built in split and join methods

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

If you'd like the newlines to be HTML line breaks that would be

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

This makes the most sense to me since you're splitting it into lines and then joining them with the newline character.

Although I think speed is less important than readability in most cases, I was curious about it in this case so I've written a quick a benchmark.

It seems that (in chrome) using str.split(",").join("\n") is faster than str.replace(/,/g, '\n'); .

查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-05-24 21:10

You can use .split() to create an array of all the parts of the string...

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"]

Now, you can do whatever you want with the different parts. Since you want to join with a new line, you can use .join() to put it back together...

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"
查看更多
我想做一个坏孩纸
5楼-- · 2020-05-24 21:13
<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>"); }
查看更多
聊天终结者
6楼-- · 2020-05-24 21:20
> 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"
查看更多
一夜七次
7楼-- · 2020-05-24 21:21

You could also replace them:

string.replace(/,/g, '\n');
查看更多
登录 后发表回答