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

Leave a Comment