const nl2br = (str) => str.replace(/\r?\n/g, "<br />");
Returns the string, all newlines (\r\n
) are replaced with XHTML-breaks <br />
.
The repository & npm package
You can find the all the utility functions from this series at github.com/martinkr/onelinecode
The library is also published to npm as @onelinecode for your convenience.
The code and the npm package will be updated every time I publish a new article.
Follow me on Twitter: @martinkr and consider to buy me a coffee
Photo by zoo_monkey on Unsplash
Top comments (5)
If the regular expression is not dynamic, you can use a RegExp literal, ie.
/\r?\n/g
.Hi Alex,
thank you for your contribution. Adjusted
replace(new RegExp("\r?\n", "g"), "<br />")
toreplace(/\r?\n/g, "<br />")
Cheers!
Coffee is good! But provided code is syntactically incorrect and I you don't have to know JS to see that, you may just count the number of opening and closing brackets. HTML elements don't actually use self-closing tags - you probably confused it with XML or React. And finally, you should never mix HTML and text content, it's really bad idea. Instead you probably should separate text into array of lines and append them one by one, additionally appending
<br>
in between.Hi Igor,
Thank you for pointing me to the syntactical misstake introduced by the last update.
I fixed the number of brackets.
Cheers!
Nice ..