What is the JavaScript string newline character?
To create a newline in a JavaScript string, \n
is your goto character. Short example:
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:
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 />
:
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?
Was this article helpful?