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 ?
Without testing on my browser try:
With the built in split and join methods
If you'd like the newlines to be HTML line breaks that would be
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 thanstr.replace(/,/g, '\n');
.You can use
.split()
to create an array of all the parts of the string...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...You could also replace them: