[JavaScript] Remove all Newlines From String

We can make use of the replace() method to replace all the newlines from a String. Let us take a look at it by an example.


Example 1:

const egStr = 'Hello \
and \
Welcome \
to \
Code2care!';

const strWithoutNewLines = egStr.replace(/[\r\n]/gm, '');
console.log(strWithoutNewLines);

Hello and Welcome to Code2care!


Let's see another example where we have newline characters (EOL) within our string.

Example 2:

const egStr = "Today \n is a good \n day!\n";
const strWithoutNewLines = egStr.replace(/[\r\n]/gm, '');
console.log(strWithoutNewLines);

Today is a good day!


Note: As the newline character can be a \n, \r or a \r\n, it is better to have a Regex that matches and removes all of such characters.

EOL CharacterDescriptionUsage
\nNewline character (Line Feed)Used in Unix and Linux Systems.
\rCarriage ReturnUsed in older Macintosh Systems.
\r\nCarriage Return + Newline (CRLF)Used in Windows and DOS Environments.


Remove All NewLine Characters from A String in JavaScript

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!