I want to strip invalid characters from a string with js.
My regex currently is as below:
var newString = oldString.replace(/([^a-z0-9 ]+)/gi, '');
i.e find anything but a-z or 0-9 and spaces independent of casing and replace with nothing - however I also want to allow underscore (_
), hyphen (-
) and dot (.
).
I attempted to update my regex as below but it is not working as expected - after I made the change I found strings with brackets () were not getting those stripped?
var newString = oldString.replace(/([^a-z0-9 .-_]+)/gi, '');
Am I missing something simple?
var newString = oldString.replace(/([^a-z0-9 ._-]+)/gi, '');
^^
Keep -
at the end as it forms a range when placed between []
. Now it is forming a range between .
and _
. Or you can escape it as well.
var newString = oldString.replace(/([^a-z0-9 ._\-]+)/gi, '');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With