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 ?
To split a string with comma, use the split() method in Java. str. split("[,]", 0);
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 .
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.
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.
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');
.
You could also replace them:
string.replace(/,/g, '\n');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With