Javascript regex returning true.. then false.. then true.. etc [duplicate] Javascript regex returning true.. then false.. then true.. etc [duplicate] ajax ajax

Javascript regex returning true.. then false.. then true.. etc [duplicate]


/^[^-_]([a-z0-9-_]{4,20})[^-_]$/gi;

You're using a g (global) RegExp. In JavaScript, global regexen have state: you call them (with exec, test etc.) the first time, you get the first match in a given string. Call them again and you get the next match, and so on until you get no match and it resets to the start of the next string. You can also write regex.lastIndex= 0 to reset this state.

(This is of course an absolutely terrible piece of design, guaranteed to confuse and cause weird errors. Welcome to JavaScript!)

You can omit the g from your RegExp, since you're only testing for one match.

Also, I don't think you want [^-_] at the front and back. That will allow any character at each end, ie. *plop! would be valid. You're probably thinking of lookahead/lookbehind assertions, but they're not available in JavaScript. (Well, lookahead is supposed to be, but it's broken in IE.) Suggest instead:

/^[a-z0-9][a-z0-9_-]{2,18}[a-z0-9]$/i


[a-z0-9-_]

This is wrong, The last - must be at the beginning or end.

[a-z0-9_-]

Whether that would cause this problem or not, I don't know.

Additional notes:

The first and last characters are allowed to be any character that isn't - or _ rather than being restricted to a-z0-9

a-z0-9 doesn't include uppercase characters. You need a-zA-Z0-9 for that.a-zA-Z0-9_ can be shortened to \w in most RegEx engines. I haven't tried it in JavaScript.