It seems you stumbled over a recent bug/regression in Chrome 75 (since build 75.0.3756.0). A bug report can be found at Issue 972850: RegExp /[\W_]/gi matches the letter S:
"RST".replace(/[\W_]/gi, "");
What is the expected behavior?
Output is "RST".
What went wrong?
Output is "RT".
The issue got merged with Issue 971636: regex /ſ/i (U+017F) matches a normal s (U+0073). A Chromium project member spots a similar case at comment #13 of that second thread:
hum...
"S".match(/[\W]/i)
null
"S".match(/[a\W]/i)
["S", index: 0, input: "S", groups: undefined]
Notice that /[a\W]/i
is just a variant on your case: the bug is not specific to the underscore: it happens as soon as you add a character in the class that is in \w
. For example, /[x\W]/i
, /[,.\W#j]/i
also trigger the problem. The g
flag is unrelated to the problem, and when you use the u
modifier, the problem disappears.
Anyway, the important news here is that the bug has been acknowledged and is fixed in Chromium 76 and possibly in a 75 bug release.
If you don't fear beta-releases, you can download the beta, which at the time of writing is 76.0.3809.46. I installed it just now and I confirm it fixes the bug.