I was bringing text in via XHR and I needed to replace the natural
\n line endings with a true
<br /> break line so that it would be legitimate HTML when injected into the DOM. It’s pretty easy, but you just need to remember: replace returns!
Since there are multiple versions of line endings, like Unix
\n but also Windows
\r\n and Mac’s old
\r, you need to replace them all just to keep your bases covered. It’s all pretty easy.
var string = 'this is a sentence.\r\n and this is another sentence about nothing!'; // notice that is reassigned? .replace returns! string = string.replace(/(\r\n|\n|\r)/gm, "<br />"); console.log(string);
This code is simple. Just a string with a line ending followed by a replace statement. I make an explicit note that
replace will return the new string, not simply mutate it in place. This caused me a bit of confusion. Also note that the gm at the end of the regular expression means that it will match globally and over different lines, just in case.
You can read the MDC documentation about String.replace too.