1

I have the following JavaScript line of code that removes characters- including commas- from a string:

return str.replace(/(?!\/)(?!\ )(?!\-)(\W)/ig, '');

How can I only take out the piece of code that removes the commas?

user3378165
  • 5,189
  • 15
  • 49
  • 86
  • Not the downvoter, but please provide some more information and expected input and output strings. – Jan Feb 11 '17 at 18:25

1 Answers1

1

The regex /(?!\/)(?!\ )(?!\-)(\W)/ig matches any character that is not a "word" character (ie. [a-zA-Z0-9_]) and the 3 lookaheads restrict also the character /, and -. The comma is removed because it is part of \W.

If you want to keep it, add another lookahead: (?!,), then your regex becomes:

return str.replace(/(?!\/)(?! )(?!-)(?!,)(\W)/g, '');

I've removed the unnecessay escape and the case insensitive flag.

This should be written as:

return str.replace(/[^\w\/, -]/g, '');
Toto
  • 83,193
  • 59
  • 77
  • 109
  • Thank you for your answer, can you explain why can't I simply remove this part: `\W` from the regex? Could you also explain what you mean by: _I've removed the unnecessary escape and the case insensitive flag._? Thank you! – user3378165 Feb 11 '17 at 18:34
  • @user3378165: In a regex you have to escape certain special characters. Space and dash are not special, so, there're no needs to escape them. You can't remove only `\W` because it rests only 3 negative lookahead that are 0-length match, you can't remove nothing by nothing! – Toto Feb 11 '17 at 18:42
  • @user3378165: For some regex basics, see http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean and http://www.regular-expressions.info/ – Toto Feb 11 '17 at 18:44
  • Working perfectly, thank you so much, I'll look into the attached link, thank you! – user3378165 Feb 11 '17 at 18:46