Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
19
rated 0 times [  24] [ 5]  / answers: 1 / hits: 56636  / 11 Years ago, wed, march 13, 2013, 12:00:00

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 ?


More From » split

 Answers
17

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


[#79630] Tuesday, March 12, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
havenbilliec

Total Points: 324
Total Questions: 106
Total Answers: 94

Location: Pitcairn Islands
Member since Fri, Oct 15, 2021
3 Years ago
;