[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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap