1

How can I get this code to return just the one false alert, since it contains a number when I'm checking that what's in the string "name" should all be lowercase alphas?

var name = "Bob1";
var i = 0; 
var name = name.toLowerCase()

for(i=0; i<name.length; i++){
  if((name.charCodeAt(i)>96) && (name.charCodeAt(i)<123)) {
    alert("true");
  } else {alert("false");}
}
1
  • 2
    . @Aquillo suggestion to use regex is a much cleaner version altogether but if you want the for loop break; is command your looking for Commented May 1, 2013 at 5:53

4 Answers 4

5

I would go with regex for this one:

if(name.match(/\d/)) {
    // this contains at least one number
}
else {
    // this doesn't contain any numbers
}

Since people will notice the upvoted answer, I will reference an even better solution for your case. This is mentioned by Ray Toal (credits / upvotes to him for this case):

Since you only want to allow undercase alpha's for your name, you can handle this directly too (this will cover issues with hyphens et cetera too):

if(name.match(/^[a-z]+$/)) {
    // this contains only undercase alpha's
}
else {
    // this contains at least one character that's not allowed
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to alert that all characters are in the range a through z you can use a regex that says that directly

alert(/^[a-z]+$/.test(name1.toLowerCase()))

You can also invert the condition and say that you want the value false if the string contains at least one non-letter:

alert(!(/[^a-z]/.test(name1.toLowerCase())))

Comments

0

add a break statement so new code would look like this inside the if statement

if((name.charCodeAt(i)>96) && (name.charCodeAt(i)<123))
 {alert("true");
   break;
 }else

... basically it just exits the for loop (same command works in while loops as well)

1 Comment

... @Aquillo suggestion to use regex is a much cleaner version altogether but if you want the for loop break; is command your looking for
0

put a break; inside the else , so that it gets out of the loop after alerting false for the first time

Comments

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.