How to remove new line character in JavaScript (\n)

In this article, we will look at different methods to remove new line character from Strings in Javascript.

Removing new line character (\n) in JavaScript

String.replace():

This method uses regex (regular expression) to detect the new line character and replace it with a space. Different operating systems have different line break characters.

Hence, the regular expression takes care of all the corner cases.

Example:

const str = 'a\ncodespeedy\narticle\ris what you\nare looking for!';
console.log(str)
const output = str.replace(/(\r\n|\n|\r)/gm, ' ');
console.log("After Replacing:"+output); 

g stands for global,i.e we want to match all occurrences 

m stands for the multiline flag

OUTPUT: 
a 
codespeedy 
article is what you 
are looking for! 
After Replacing:a codespeedy article is what you are looking for!

Using split() and join():

This method will first split the strings into an array of substrings based on line break like this {a,codespeedy,article,is,what,you,are,looking,for} and then we will join array back into a string using the join method

Example:

const str = 'a\ncodespeedy\narticle is what you\nare looking for';
console.log(str)
const output = str.split('\n').join(' ')
console.log("After Replacing:"+output); 
Output:-
a
codespeedy
article is what you
are looking for
After Replacing:a codespeedy article is what you are looking for

Using loops:

In this, we loop through every character of the string and compare with line break characters if there are not present then we add the character in the new string.

Example:

const str = 'a\n codespeedy\r article is what you\r\n are looking for!!!!';
var newstr = "";
for( var i = 0; i < str.length; i++ ) 
    if( !(str[i] == '\n' || str[i] == '\r' || str[i]=='\r\n' ) )
        newstr += str[i];
console.log(newstr)
OUTPUT:
a codespeedy article is what you are looking for!!!!

String.trim():

If you want to remove new line character from the beginning and end of the string, you can use this function

OUTPUT:
a codespeedy
article is what you are looking for


After Replacing:a codespeedy
article is what you are looking for

These are some of the methods to remove new line character in JS.

Leave a Reply

Your email address will not be published. Required fields are marked *