Split string with commas to new line

前端 未结 6 2159
终归单人心
终归单人心 2021-02-04 19:11

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
         


        
6条回答
  •  情话喂你
    2021-02-04 19:31

    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("
    ")

    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'); .

提交回复
热议问题