0

I'm very stumped here. I'm trying to take some server-side PHP and introduce some JavaScript that does the same thing - giving hints to the user as they type. I have the following, which is attempting to find all lowercase letters, uppercase letters, and numbers 0 or more times; it then deletes those characters, leaving behind a string containing everything else. I then take the length of this and compare it to a variable maxSymbols, which is 5.

I cannot get this to evaluate properly... what am I missing here?

else if(passwordValue.replace(/([a-zA-Z0-9])*/, '').length > maxSymbols){

// Check the maximum number of symbols in the password.
    document.getElementById("passwordHint").innerHTML = "You've used too many symbols, " + maxSymbols + " is the maximum.";
    document.getElementById("passwordHint").style.color = "red";

}

2 Answers 2

1

You are missing the g modifier for your regular expression. Without the g, you are only replacing the first match.

Try if(passwordValue.replace(/([a-zA-Z0-9])*/g, '').length > maxSymbols).

Hope this helps,

Pete

Sign up to request clarification or add additional context in comments.

3 Comments

Both answers work great, thanks guys/gals. This just proves that I have much to learn about regex syntax between languages.
Are these flags unique to JavaScript? It's interesting that my PHP regex works as I intended without the 'g' flag.
@patrickn js does have it's own flavor of js. I don't know how close it is to PHP's but they are going to have differences.
0
.replace(/([a-zA-Z0-9])*/, '')

should be

.replace(/[a-zA-Z0-9]/g, '')

and you should be good. :) What your are searching for in the first one is 0 or more of those characters together. What you need is that character class replaces globally (the g).

2 Comments

Interesting, both pages I am using as a reference don't show the /g flag. Unless I'm missing it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.