Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string with commas to new line

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 ?

like image 561
Andy Avatar asked Mar 13 '13 02:03

Andy


People also ask

How do you split a string with comma separated?

To split a string with comma, use the split() method in Java. str. split("[,]", 0);

How do I split a string into a new line?

Split String at Newline When the literal \n represents a newline character, convert it to an actual newline using the compose function. Then use splitlines to split the string at the newline character. Create a string in which two lines of text are separated by \n .

How do you replace commas with new lines?

Select the cells containing the commas you need to replace with newlines, then press the Alt + F11 keys simultaneously to open the Microsoft Visual Basic for Applications window. 3. Press the F5 key or click the Run button to run the code. Then all commas in selected cells are replaced with newlines immediately.

How do I change a comma separated string to a number?

To convert a comma separated string to a numeric array:Call the split() method on the string to get an array containing the substrings. Use the map() method to iterate over the array and convert each string to a number. The map method will return a new array containing only numbers.


2 Answers

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

like image 168
Benjamin Gruenbaum Avatar answered Oct 03 '22 23:10

Benjamin Gruenbaum


You could also replace them:

string.replace(/,/g, '\n');
like image 43
Blender Avatar answered Oct 03 '22 22:10

Blender