Explain Codes LogoExplain Codes Logo

What is the JavaScript string newline character?

javascript
prompt-engineering
functions
regex
Nikita BarsukovbyNikita Barsukov·Jan 1, 2025
TLDR

To create a newline in a JavaScript string, \n is your goto character. Short example:

let greeting = "Hello\nWorld!";

Displays on the screen as:

Hello
World!

Dealing with different environments

In JavaScript, \n is the most commonly used newline character. However, it's important to mention that Internet Explorer 8 and Opera 9 on Windows use \r\n. In modern days, all browsers and JS engines convert \r\n and \r to \n when working with JavaScript strings. In the majority of cases, you can write your code using \n and expect the same result cross-browser.

Multiple newline formats handling

Now, you might encounter different formats of newlines while processing text. Fret not, a regex pattern like /\r\n|\r|\n/g will be your knight in shining armor:

let text = "Roses are red\r\nViolets are blue\rSo are you\nKidding me dude?"; let lines = text.split(/\r\n|\r|\n/g); //["Roses are red", "Violets are blue", "So are you", "Kidding me dude?"] // A poet, really? 🙄

This method catches all newline monsters: \r\n, \r, and \n. Well done, knight!

Form submission encoding

During form submissions, newline characters transform into %0D%0A in URL encoding, courtesy of all browsers. Just one more thing for JavaScript developers to remember. 😉

Working with HTML

In your tussles with HTML, remember that the HTML specification resides on planet \n within a text area. Irrespective of your JavaScript or HTML source file line endings, newline in HTML remains immune to changes. To convert newlines to a HTML-friendly format, replace them with <br />:

let poem = "Hello..\nAre you a poem?"; let displayedPoem = poem.replace(/\r\n|\r|\n/g, "<br />"); // displayedPoem = 'Hello..<br />Are you a poem?'

Multiline strings without newline characters

Thanks to template literals, JavaScript now sports multiline strings without the explicit use of newline characters. How cool is that?

let phrase = ` This string skips multiple lines and it doesn't even need \\n. `; // Round of applause for JS, everybody! 🎉