Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex for cleaning string value

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?

like image 990
Ctrl_Alt_Defeat Avatar asked Mar 17 '23 04:03

Ctrl_Alt_Defeat


1 Answers

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, '');
like image 108
vks Avatar answered Apr 25 '23 10:04

vks