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);
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);
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 Character | Description | Usage |
|---|---|---|
\n | Newline character (Line Feed) | Used in Unix and Linux Systems. |
\r | Carriage Return | Used in older Macintosh Systems. |
\r\n | Carriage Return + Newline (CRLF) | Used in Windows and DOS Environments. |

Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!