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

Can anyone help me with this regex? I need something that SHOULD:

0-9 a-d AZ apostrophe hyphen space

But disallow all other special characters.

I have this, but it doesn't work:

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

      

Thanks for any help!

+2


source to share


4 answers


You have to remove the double quotes around the regex:

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

      



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

+5


source


You can also remove the outer slashes and pass it to the constructor RegExp

.

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

      



Which is equivalent to syntax /pattern/modifiers

(the second argument is an optional modifier character string). The character class \w

matches alphanumeric characters, including the underscore, so I think you can shorten your pattern a bit by using that.

^[\w \-']+$

      

+3


source


If you want to match underscores as well as alphanumeric characters (as your code suggests), you can use

"regex": /^[\w '-]+$/,

      

Also, check out this regex checking tool online .

0


source


regExp = /^[0-9A-Za-z\$ ]{0,30}$/;

      

-2


source







All Articles