Reputation: 28505
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),"");
Upvotes: 13
Views: 23774
Reputation: 10342
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,'');
Upvotes: 25
Reputation: 3055
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.
Upvotes: 12
Reputation: 160903
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, '');
Upvotes: 2