638

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Wingblade
  • 9,585
  • 10
  • 35
  • 48
  • Possible duplicate of [How do I replace all line breaks in a string with
    tags?](https://stackoverflow.com/questions/784539/how-do-i-replace-all-line-breaks-in-a-string-with-br-tags)
    – Jun Oct 26 '18 at 00:32

21 Answers21

759

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.

Robert Smit
  • 118
  • 6
Eremite
  • 7,995
  • 2
  • 13
  • 6
  • 41
    Why is having the separate `\r\n` *and* `\n` *and* `\r` better than just `/[\n\r]/g`? Surely this is slower than it should be, as it only needs to check each character against the set of two possible options. – iCollect.it Ltd Dec 11 '14 at 17:58
  • 3
    When parsing returned data from memcached in node.js using /[\n\r]/g did the trick for me. Thanks Gone Coding! The option in the answer butchered it. – Kyle Coots Sep 21 '18 at 03:11
  • * Apple stopped using carriage return line endings in MacOS X. – cael ras Jan 09 '22 at 07:04
635

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.)

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
PointedEars
  • 14,752
  • 4
  • 34
  • 33
  • 22
    For the sake of completeness, it should be noted that there are four different new line characters in Unicode: `\u000a` or `\n`, which is a line feed; `\u000d` or `\r`, which is a carriage return; `\u2028`, a line separator; and `\u2029`, a paragraph separator. In practice though, the regex you posted is sufficient in most cases. – Mathias Bynens May 30 '12 at 17:02
  • 5
    @MathiasBynens Thanks, but U+2028 and U+2029 explicitly do _not_ constitute line breaks in HTML (4.01), which the DOM tree and the textarea's live value are based on: http://www.w3.org/TR/html4/struct/text.html#whitespace – PointedEars May 30 '12 at 17:12
  • 5
    @PointedEars Yes, but HTML serialization doesn’t occur when setting the textarea’s `.value` dynamically, e.g. `textarea.value = 'a\u2029b'; textarea.value.charAt(1) == '\u2029'; // true`. But this is probably an edge case — as I said, in most cases your regex is sufficient. – Mathias Bynens May 30 '12 at 18:58
  • 2
    @MathiasBynens Because U+2028 and U+2029 do not constitute line breaks in HTML (4.01), that assignment does *not* display two lines in the textarea with any major DOM implementation and layout engine. So nobody in their right mind would make such an assignment in the first place. – PointedEars Jun 28 '12 at 22:44
  • 1
    I had to escape the backslash to get this working for me i.e. textIn.replace(/(\\r\\n|\\n|\\r)/gm, ""). +1 still. Thank you – Crab Bucket May 03 '17 at 09:01
  • 2
    @CrabBucket You’re welcome. But your modification only works if there are *literal* (already *escaped*) “\r” and “\n” in the string, or if the code is passed to `eval()` or something like it (which you should avoid). – PointedEars May 04 '17 at 23:27
178

var str = " \n this is a string \n \n \n"

console.log(str);
console.log(str.trim());

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.

Suresh Prajapati
  • 3,991
  • 5
  • 26
  • 38
RobW
  • 10,184
  • 4
  • 41
  • 40
86

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 \n and \r. This regex will replace them all.

Kendall Frey
  • 43,130
  • 20
  • 110
  • 148
  • I think this will only replace the first occurence – Sebas May 29 '12 at 19:10
  • 8
    `/\n|\r/g` is more efficiently written `/[\n\r]/g` or even `/[\n\r]+/g`. Avoid alternation unless you absolutely need it. – PointedEars May 29 '12 at 19:56
  • 1
    Not sure if this is ment to be a complaint. It does what I said: remove EVERYTHING not in that HEX range. What chars that are depends on the char set of course, but this post was about ASCII. – omni Jan 23 '19 at 23:11
56

The simplest solution would be:

let str = '\t\n\r this  \n \t   \r  is \r a   \n test \t  \r \n';
str = str.replace(/\s+/g, ' ').trim();
console.log(str); // logs: "this is a test"

.replace() with /\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:
[ \f\n\r\t\v​\u00a0\u1680​\u2000​-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]

RiZKiT
  • 2,107
  • 28
  • 23
Freezystem
  • 4,494
  • 1
  • 32
  • 35
  • 1
    Awesome, but I get it working re-assigning the variable: `str = str.replace(/\s+/g, ' ').trim();` – Fred K Jan 12 '20 at 09:28
24

If you want to remove all control characters, including CR and LF, you can use this:

myString.replace(/[^\x20-\x7E]/gmi, "")

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.

omni
  • 4,104
  • 8
  • 48
  • 67
19

This will replace the line break by empty space.

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

Read more on this article.

4b0
  • 21,981
  • 30
  • 95
  • 142
Jaman-Dedy
  • 567
  • 5
  • 3
18
var str = "bar\r\nbaz\nfoo";

str.replace(/[\r\n]/g, '');

>> "barbazfoo"
Gordon Freeman
  • 891
  • 7
  • 5
17

To remove new line chars use this:

yourString.replace(/\r?\n?/g, '')

Then you can trim your string to remove leading and trailing spaces:

yourString.trim()
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Si7ius
  • 676
  • 6
  • 14
11

USE THIS FUNCTION BELOW AND MAKE YOUR LIFE EASY

The easiest approach is using regular expressions to detect and replace newlines in the string. In this case, we use replace function along with string to replace with, which in our case is an empty string.

function remove_linebreaks( var message ) {
    return message.replace( /[\r\n]+/gm, "" );
}

In the above expression, g and m are for global and multiline flags

vishu2124
  • 4,243
  • 2
  • 14
  • 10
11

I often use this regex for (html) strings inside jsons:

replace(/[\n\r\t\s]+/g, ' ')

The strings come from a html editor of a CMS or a i18n php. The common scenarios are:

- lorem(.,)\nipsum
- lorem(.,)\n ipsum
- lorem(.,)\n
  ipsum
- lorem   ipsum
- lorem\n\nipsum
- ... many others with mixed whitespaces (\t\s) and even \r

The regex avoids this ugly things:

lorem\nipsum    => loremipsum
lorem,\nipsum   => lorem,ipsum
lorem,\n\nipsum => lorem,  ipsum
...

Surely not for all use cases and not the fastest one, but enough for most textareas and texts for websites or webapps.

aProgger
  • 696
  • 1
  • 8
  • 24
9

The answer provided by PointedEars is everything most of us need. But by following Mathias Bynens's answer, I went on a Wikipedia trip and found this: https://en.wikipedia.org/wiki/Newline.

The following is a drop-in function that implements everything the above Wiki page considers "new line" at the time of this answer.

If something doesn't fit your case, just remove it. Also, if you're looking for performance this might not be it, but for a quick tool that does the job in any case, this should be useful.

// replaces all "new line" characters contained in `someString` with the given `replacementString`
const replaceNewLineChars = ((someString, replacementString = ``) => { // defaults to just removing
  const LF = `\u{000a}`; // Line Feed (\n)
  const VT = `\u{000b}`; // Vertical Tab
  const FF = `\u{000c}`; // Form Feed
  const CR = `\u{000d}`; // Carriage Return (\r)
  const CRLF = `${CR}${LF}`; // (\r\n)
  const NEL = `\u{0085}`; // Next Line
  const LS = `\u{2028}`; // Line Separator
  const PS = `\u{2029}`; // Paragraph Separator
  const lineTerminators = [LF, VT, FF, CR, CRLF, NEL, LS, PS]; // all Unicode `lineTerminators`
  let finalString = someString.normalize(`NFD`); // better safe than sorry? Or is it?
  for (let lineTerminator of lineTerminators) {
    if (finalString.includes(lineTerminator)) { // check if the string contains the current `lineTerminator`
      let regex = new RegExp(lineTerminator.normalize(`NFD`), `gu`); // create the `regex` for the current `lineTerminator`
      finalString = finalString.replace(regex, replacementString); // perform the replacement
    };
  };
  return finalString.normalize(`NFC`); // return the `finalString` (without any Unicode `lineTerminators`)
});
futz.co
  • 177
  • 1
  • 2
  • 8
  • 4
    First - for people finding this not using JS - "most" RE flavors support `\R` which is "all" linefeeds. Secondly - why not simply `someString.replace(new RegExp(lineTerminators.join('|')), '');` – SamWhan Jun 08 '17 at 14:41
  • @ClasG, you make a good point. I think my line of thought when I wrote this was to only run `replace()` for the `lineTerminators` that existed in the string for performance reasons. – futz.co Jun 08 '17 at 16:00
9

Simple we can remove new line by using text.replace(/\n/g, " ")

const text = 'Students next year\n GO \n For Trip \n';
console.log("Original : ", text);

var removed_new_line = text.replace(/\n/g, " ");
console.log("New : ", removed_new_line);
Rohit Tagadiya
  • 3,373
  • 1
  • 25
  • 25
5

A linebreak in regex is \n, so your script would be

var test = 'this\nis\na\ntest\nwith\newlines';
console.log(test.replace(/\n/g, ' '));
h2ooooooo
  • 39,111
  • 8
  • 68
  • 102
5

I am adding my answer, it is just an addon to the above, as for me I tried all the /n options and it didn't work, I saw my text is comming from server with double slash so I used this:

var fixedText = yourString.replace(/(\r\n|\n|\r|\\n)/gm, '');
chaya D
  • 129
  • 1
  • 13
2

Try the following code. It works on all platforms.

var break_for_winDOS = 'test\r\nwith\r\nline\r\nbreaks';
var break_for_linux = 'test\nwith\nline\nbreaks';
var break_for_older_mac = 'test\rwith\rline\rbreaks';

break_for_winDOS.replace(/(\r?\n|\r)/gm, ' ');
//output
'test with line breaks'

break_for_linux.replace(/(\r?\n|\r)/gm, ' ');
//output
'test with line breaks'

break_for_older_mac.replace(/(\r?\n|\r)/gm, ' ');
// Output
'test with line breaks'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
2

If it happens that you don't need this htm characte &nbsp shile using str.replace(/(\r\n|\n|\r)/gm, "") you can use this str.split('\n').join('');

cheers

Jaman-Dedy
  • 567
  • 5
  • 3
2

1st way:

const yourString = 'How are you \n I am fine \n Hah'; // Or textInput, something else

const newStringWithoutLineBreaks = yourString.replace(/(\r\n|\n|\r)/gm, "");

2nd way:

const yourString = 'How are you \n I am fine \n Hah'; // Or textInput, something else

const newStringWithoutLineBreaks = yourString.split('\n').join('');
2

This will remove all your newlines, spaces, unnecessary characters

str = '\n  \n\n\n\n\n\n\n\n\n\n\n\n  \n    \n      \n    \n    Books\n  \n    \n  \n  \n\n\n';
console.log(str);
var output = str.replace(/\n|\r|\W/g, "");

console.log(output);

'Books'

yPhil
  • 8,049
  • 4
  • 57
  • 83
0

On mac, just use \n in regexp to match linebreaks. So the code will be string.replace(/\n/g, ''), ps: the g followed means match all instead of just the first.

On windows, it will be \r\n.

kobako
  • 636
  • 5
  • 11
-4

const text = 'test\nwith\nline\nbreaks'

const textWithoutBreaks = text.split('\n').join(' ')