How to remove all line breaks from a string
I have a text in a textarea and I read it out using the .value attribute.
Now I would like to remove all linebreaks (the character that is produced when you press Enter) from my text now using .replace with a regular expression, but how do I indicate a linebreak in a regex?
If that is not possible, is there another way?
This is probably a FAQ. Anyhow, 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
If you want to match all newlines in a string, use a global match,
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.)
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
someText = someText.replace(/(\r\n|\n|\r)/gm, "");
That should remove all kinds of line breaks.
String.trim() removes whitespace from the beginning and end of strings… including newlines.
const myString = " \n \n\n Hey! \n I'm a string!!! \n\n"; const trimmedString = myString.trim(); console.log(trimmedString); // outputs: "Hey! \n I'm a string!!!"
Here’s an example fiddle: http://jsfiddle.net/BLs8u/
NOTE! it only trims the beginning and end of the string, not line breaks or whitespace in the middle of the string.
You can use
\n in a regex for newlines, and
\r for carriage returns.
var str2 = str.replace(/\n|\r/g, "");
Different operating systems use different line endings, with varying mixtures of
\r. This regex will replace them all.
If you want to remove all control characters, including CR and LF, you can use this:
It will remove all non-printable characters. This are all characters NOT within the ASCII HEX space
0x20-0x7E. Feel free to modify the HEX range as needed.
The simplest solution would be:
let str = '\t\n\r this \n \t \r is \r a \n test \t \r \n'; str.replace(/\s+/g, ' ').trim(); console.log(str); // logs: "this is a test"
/\s+/g regexp is changing all groups of white-spaces characters to a single space in the whole string then we
.trim() the result to remove all exceeding white-spaces before and after the text.
Are considered as white-spaces characters: