views:

59

answers:

4

How can I quickly validate if 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.

+11  A: 

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
gnarf
The space regex, I know it works, but I prefer to use \s to show the space character...
Limo Wan Kenobi
`\s` and its cousins inside of character sets is not widely supported in other regular expression flavors, so I have a tendency to avoid it, although it will work fine in JavaScript.
gnarf
The `i` flag may also be appropriate.
Justin Johnson
@Justin Johnson - Yup - `/^[a-z()]+$/i.test(str);` works too.
gnarf
+1  A: 

If memory serves this should work in javascript:

function containsOnlyLettersOrParenthesis(str)
(
    return str.match(/^([a-z\(\)]+)$/i);
)
Kris
no need to escape the `()` in the character set.
gnarf
A: 

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

Limo Wan Kenobi
A: 

Here you go:

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