How to remove all line breaks from a string How to remove all line breaks from a string javascript javascript

How to remove all line breaks from a string


How you'd find a line break varies between operating system encodings. Windows would be \r\n, but Linux just uses \n and Apple uses \r.

I found this in JavaScript line breaks:

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

That should remove all kinds of line breaks.


Line breaks (better: newlines) can be one of Carriage Return (CR, \r, on older Macs), Line Feed (LF, \n, on Unices incl. Linux) or CR followed by LF (\r\n, on WinDOS). (Contrary to another answer, this has nothing to do with character encoding.)

Therefore, the most efficient RegExp literal to match all variants is

/\r?\n|\r/

If you want to match all newlines in a string, use a global match,

/\r?\n|\r/g

respectively. Then proceed with the replace method as suggested in several other answers. (Probably you do not want to remove the newlines, but replace them with other whitespace, for example the space character, so that words remain intact.)


var str = " \n this is a string \n \n \n"console.log(str);console.log(str.trim());