Remove all occurences of new lines and tabs

11,900

Solution 1

The regexpr delimiter is /, so you have the "or" | out of the expression. If you want to join them try with

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

By the way, the tab character is \t in a regexp, so if you want to remove all tabs and new lines you can use str.replace(/[\t\n\r]/gm,''); Said this, if with "tab" you mean any identation including "4 white spaces", then use str.replace(/ {4}|[\t\n\r]/gm,'');

Solution 2

Instead of all the OR operators, you might want to just group them like this:

str = "Hello\n" +
      "there    stranger!";

str.replace(/[\r\n\t]/g, "")
// "Hellotherestranger!"

The [ and ] group means 'any character from within this group', it's cleaner than all the OR expressions.

Solution 3

You should do like below (combine two regex into one):

str = str.replace(/  |\r\n|\n|\r/gm, '');

For 2 space, you could also write:

str = str.replace(/ {2}|\r\n|\n|\r/gm, '');
Share:
11,900
Bram Vanroy
Author by

Bram Vanroy

Currently working on machine translation and translation difficulty. I'm also interested in a couple of other things, such as linguistics; natural language processing; artificial intelligence, deep learning; music, drums and bass more specifically; design & UI.

Updated on June 25, 2022

Comments

  • Bram Vanroy
    Bram Vanroy almost 2 years

    I'm still in the process of learning some decent regex but I would have thought this would work.

    This works:

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

    But a shorter version of this, does not. Where did I go wrong?

    str.replace((/  /g)|(/(\r\n|\n|\r)/gm),"");
    
  • Mr. Polywhirl
    Mr. Polywhirl about 10 years
    I would place the space in brackets, it looks nicer: str = replace(/[ ]{2}|\r\n|\n|\r/gm, '');
  • Bram Vanroy
    Bram Vanroy about 10 years
    I like this answer, especially because you explain everything very well. That's good for a beginner in RegEx, as I am in.
  • rad
    rad almost 4 years
    Using the recommended way to include 4 spaces is buggy, as it will incorrectly match to the literal number 4. Use this instead: str.replace(/ {4}|[\t\n\r]/gm,'');.
  • Austin737
    Austin737 almost 4 years
    This is a great recommendation, especially if you were going to be removing other characters in addition to tabs and newlines