Ad

Not Sure Why This Regex Is Returning True

- 1 answer

Trying to use this regex to verify usernames and this is what I have :

var goodUsername  = /[a-zA-Z0-9_]/g;

console.log(goodUsername.test("HELO $"));

But wether or not I have $ in there it returns true. Not sure why.

I basically only want letters, numbers and _ in usernames and that's it

It seems to work here https://regex101.com/r/nP4iG7/1

Ad

Answer

The RegEx that you use searches any match in the subject string. In your case HELO matches the criteria. If you like to apply the criteria to the whole string you should define the string begin and end using

var goodUsername  = /^[a-zA-Z0-9_]+$/;
console.log(goodUsername.test("HELO $"));//false
Ad
source: stackoverflow.com
Ad