How to Remove All Line Breaks from a String in JavaScript

There are three types of line breaks, CRLF, LF and CR, which are represented by the following statements:

 

  • \r\n – a CRLF line break used by Windows machines.
  • \n – a LF (Line Feed) line break used by all other systems.
  • \r – a CR (Carriage Return) line break.

 

To remove all possible line breaks from a string in JavaScript, we will need to find all of the above statements in the string and replace them with an empty string.

 

The easiest way to do this is with a Regular Expression inside a JavaScript .replace() function like this:

 

var string = 'A line\r\n, another line \n, and another line\r';

var result = string.replace(/(\r\n|\n|\r)/gm, "");

console.log(result);
A line, another line , and another line

 

If you don't want to use RegEx, you could loop through each character in the string and add each character to a new string if it is not one of the line break statements.

 

var string = 'A line\r\n, another line \n, and another line\r';

var result = ""; 

for( var i = 0; i < string.length; i++ ) {

  if (!(string[i] == '\n' || string[i] == '\r')) {

      result += string[i];
  }
}

console.log(result);
A line, another line , and another line