← coderrocketfuel.com

Remove All Line Breaks From a String in JavaScript

How can you remove all line break characters from a string in JavaScript?

You can do that using replace() with a regular expression:

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

That regular expression will remove all instances of \r\n, \n, or \r in your string.

Those three versions will cover different encodings for these operating systems:

  • Windows (\r\n)
  • Linux (\n)
  • Apple (\r)

You can also remove just instances of \n, \r, or \r\n line breaks in your string with this:

string.replace(/\n/gm, "");
string.replace(/\r/gm, "");
string.replace(/\r\n/gm, "");

Each of those would only remove one of the three types of line-break characters.

Thanks for reading and happy coding!