开发者

My code does not work - im trying to see if the first letter is a capital :: JavaScript

Im trying to see if the first letter of a string is a Capital.

Here is my HTML

Test:<br/>
<input type="text" name="Testr" size="25" />

And here is my JavaScript

var namer=document.logOn.Testr.value;

if(/[^A]/.test(namer)){             
     alert("CHOMP CHOMP");
  开发者_如何学Python      return false;
}

I dont understand why my code doesnt work?

What do you guys think?


Your regular expression looks for anything that's not capital "A". Try:

if (/^[A-Z]/.test(namer)) {
  // starts with a capital letter
}
else {
  // starts with something else
}

What I changed was:

  • The "^" needed to be outside the "[]" to indicate that you're checking the start of the value
  • The range needed to cover all the upper-case letters, not just "A"

Note that if you're interested in matching upper-case characters from elsewhere in the Unicode space, you'll have to include those explicitly.


Try using this regex instead:

/^[A-Z]{1}/


Your regular expression is incorrect. You're checking that namer doesn't begin with the capital letter A. You need to use a range instead:

if(/^[A-Z]/.test(namer)){             
     alert("CHOMP CHOMP");
        return false;
}


see the answer from this question: How to make it so a string has to start with a capital letter with JavaScript?

you're only testing the capital letter A...


Try

if(/^[A-Z]/.test(namer)){             
     alert("CHOMP CHOMP");
        return false;
}


Something like this:

<input type="text" id="Testr" size="25" />

...

var namer = document.getElementById('Testr').value;

if(/^[A-Z]/.test(namer)){
    alert("CHOMP CHOMP");
    return false;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜