Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Javascript 0-9a-zA-Z plus whitespace, commas etc

Can anyone help me with this regex? I need something which will ALLOW:

0-9 a-z A-Z spaces hyphens apostrophes

But disallow all other special characters.

I've got this, but it's not working:

"regex":"/^[0-9a-zA-Z/ /-'_]+$/",

Thanks for any help!

like image 468
MrFidge Avatar asked Oct 29 '25 07:10

MrFidge


2 Answers

You should remove the double quotes around the regex:

"regex": /^[0-9a-zA-Z \-'_]+$/,

Also make sure you use backslashes to escape special characters, not forward slashes.

like image 170
Philippe Leybaert Avatar answered Oct 30 '25 23:10

Philippe Leybaert


You could alternatively remove the outer forward slashes and pass it to the constructor of RegExp.

"regex" : new RegExp("^[0-9a-zA-Z \-'_]+$")

Which is equivalent to the /pattern/modifiers syntax (the second argument is an optional string of modifier characters). The \w character class matches alphanumeric characters, including underscore, so I think you can shorten your pattern quite a bit by using it.

^[\w \-']+$
like image 38
bambams Avatar answered Oct 30 '25 23:10

bambams