DEV Community

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

Posted on

5

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


Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

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 ..

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay