开发者

Validating alphabetic only string in javascript

How can I quickly validate i开发者_如何学Cf a string is alphabetic only, e.g

var str = "!";
alert(isLetter(str)); // false

var str = "a";
alert(isLetter(str)); // true

Edit : I would like to add parenthesis i.e () to an exception, so

var str = "(";

or

var str = ")";

should also return true.


Regular expression to require at least one letter, or paren, and only allow letters and paren:

function isAlphaOrParen(str) {
  return /^[a-zA-Z()]+$/.test(str);
}

Modify the regexp as needed:

  • /^[a-zA-Z()]*$/ - also returns true for an empty string
  • /^[a-zA-Z()]$/ - only returns true for single characters.
  • /^[a-zA-Z() ]+$/ - also allows spaces


Here you go:

function isLetter(s)
{
  return s.match("^[a-zA-Z\(\)]+$");    
}


If memory serves this should work in javascript:

function containsOnlyLettersOrParenthesis(str)
(
    return str.match(/^([a-z\(\)]+)$/i);
)


You could use Regular Expressions...

functions isLetter(str) { return str.match("^[a-zA-Z()]+$"); }

Oops... my bad... this is wrong... it should be

functions isLetter(str) {
    return "^[a-zA-Z()]+$".test(str);
}

As the other answer says... sorry

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜