DEV Community

Cover image for 1 line of code: How to convert \newlines to <breaks />
Martin Krause
Martin Krause

Posted on

1 line of code: How to convert \newlines to <breaks />

const nl2br = (str) => str.replace(/\r?\n/g, "<br />");
Enter fullscreen mode Exit fullscreen mode

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


Subscribe to the weekly modern frontend development newsletter


Top comments (5)

Collapse
 
lexlohr profile image
Alex Lohr

If the regular expression is not dynamic, you can use a RegExp literal, ie. /\r?\n/g.

Collapse
 
martinkr profile image
Martin Krause

Hi Alex,

thank you for your contribution. Adjusted replace(new RegExp("\r?\n", "g"), "<br />") to replace(/\r?\n/g, "<br />")

Cheers!

Collapse
 
snigo profile image
Igor Snitkin

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.

Collapse
 
martinkr profile image
Martin Krause

Hi Igor,

Thank you for pointing me to the syntactical misstake introduced by the last update.
I fixed the number of brackets.

Cheers!

Collapse
 
crearesite profile image
WebsiteMarket

Nice ..