Jim Peeters Jim Peeters - 5 months ago 7
Javascript Question

Why is this regular expression in javascript still allowing special characters [a-zA-Z1-9 ]?

I don't want to allow special characters but this regular expression still allows them, what am I doing wrong?

When i type for name : '&é"é&'é"&'&é"'a' It still gives back 'true'

name.match(/[a-zA-Z1-9 ]/))


You need to use RegExp#test with anchors ^ and $.

/^[a-zA-Z1-9 ]+$/.test(name)

String#match return an array if match is found. In your case, a at the end of the string is found and array is returned. And array is truthy in the Javascript. I believe, the array is converted to Boolean, so it returned true.