-2

So, I need you match all the characters from A-z in my code and then get the length of it. Basically I need to use a match in the string value, and then get the length of that match. Right now it doesn't work at all. If I remove the length, I get a null value.

Here is the code of it so far:

var username = "A1KJ!PNSG2Q0";

if(username.match(/^[A-z]+$/g).length < 5) {
    alert("Yay!")
}

Thank you in advanced to anyone helps!

UnderMyWheel
  • 241
  • 2
  • 11
  • What do you want your code to do? What is it doing that is different from the desired behavior? – AmericanUmlaut Mar 02 '16 at 21:51
  • Basically do you want to count the number of A-Z a-z letters in the string? – Nayuki Mar 02 '16 at 21:52
  • Yes, I want to count the number of A-Z and a-z letters in the string. Right now it doesn't work and does nothing on the page and the code stops executing after it since it's an if statement and it's not working. – UnderMyWheel Mar 02 '16 at 21:53
  • This is a duplicate of http://stackoverflow.com/questions/881085/count-the-number-of-occurences-of-a-character-in-a-string-in-javascript – AmericanUmlaut Mar 02 '16 at 21:55
  • 2
    Take out the caret "^" and "$" from your regular expression. That should match each character one by one and return a list of your expected results – repzero Mar 02 '16 at 22:16
  • Did not work when I replaced the caret to a dollar sign – UnderMyWheel Mar 02 '16 at 22:23
  • I mean take out the caret AND the dollar sign. It should count all characters that matches your regex bracketed class – repzero Mar 02 '16 at 22:25
  • That worked, however there's an issue. When it hits a number or special character, it stops matching everything else after that. – UnderMyWheel Mar 02 '16 at 22:28

1 Answers1

1

The correct regex is /[A-z]{1}/g. You want to count the number of occurences for each character that matches [A-z]. Without {0} it will only count blocks of characters, for example PNSG will count as one.

var username = "A1KJ!PNSG2Q0";

document.write('Matches: '+username.match(/[A-z]{1}/g)+'<br>')
if(username.match(/[A-z]{1}/g).length < 5) {
    document.write('Yeah' )
}
else
{
document.write('Computer says No'+'<br>' )
}


var username = "A1KJ!7543210";

document.write('Matches: ' + username.match(/[A-z]{1}/g)+'<br>')
if(username.match(/[A-z]{1}/g).length < 5) {
    document.write('Yeah' )
}
Alex
  • 21,273
  • 10
  • 61
  • 73