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?

1
  • Not the downvoter, but please provide some more information and expected input and output strings. Commented Feb 11, 2017 at 18:25

1 Answer 1

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, ''); 
Sign up to request clarification or add additional context in comments.

4 Comments

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: 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!
@user3378165: For some regex basics, see stackoverflow.com/questions/22937618/… and regular-expressions.info
Working perfectly, thank you so much, I'll look into the attached link, thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.