Character set in regex


why does this code matches both \W and _ if it is inside a character set [] ?

does’t s character set matches this or that but never 2 things?

var str = "fdfd.////__/f";
console.log(str.replace(/[\W_]/gi,""); // will replace both \W and _

It is only matching one at a time, but because you are using the greedy flag, it will match multiple times.

What are wanting to do with regex?

It is actually a global flag not greedy.

hope this helps answers your question

i want to find everything that is not words and underscores _ .

i want to replace them with “” with the replace method.
what i don’t understand is why it matches this \W and this _ if it is inside brackets []

I thought that brackets find one thing at a time only.

They do (only match one character), just reread what was already written and check out thisiswhale’s link, where you’ll have the matching coloured.

g means repeat, if that makes it easier to understand.

What string output did you expect? What you describe matches your code …

hey @lynxlynxlynx,

doesn’t g means global? also the regex website says it doesn’t return after a match.


the output is fine. I just try to understand what happened…

Of course it stands for global … And because it doesn’t stop after the first match, it repeats the match after each substitution, checking if there’s still anything to do — until it reaches the end of the input string. IOW it’s killing the bad characters one at a time.

thanks mate i got it

Tomato toh-mah-toh, depending on the context you learned regular expressions in.

It’s most useful/least ambiguous to refer to the g flag as “global”, because:

  • “Greedy” already stands for a different concept in regexes
  • The same is true of “repeat”

For example, the regex /(ab){5}/ matches 5 “ab” substrings in a row (i.e. the substring must repeat 5 times). If we change it to /(ab){1,5}/, it matches as many as it can up to 5 (i.e. it’s greedy).