Javascript 在javascript中验证仅字母字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2450641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Validating alphabetic only string in javascript
提问by Click Upvote
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
编辑:我想将括号 ie 添加()到异常中,所以
var str = "(";
or
或者
var str = ")";
should also return true.
也应该返回true。
回答by gnarf
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
/^[a-zA-Z()]*$/- 对于空字符串也返回 true/^[a-zA-Z()]$/- 仅对单个字符返回 true。/^[a-zA-Z() ]+$/- 也允许空格
回答by Vlad
Here you go:
干得好:
function isLetter(s)
{
return s.match("^[a-zA-Z\(\)]+$");
}
回答by Kris
If memory serves this should work in javascript:
如果内存可用,这应该在 javascript 中工作:
function containsOnlyLettersOrParenthesis(str)
(
return str.match(/^([a-z\(\)]+)$/i);
)
回答by Edgar Hernandez
You could use Regular Expressions...
您可以使用正则表达式...
functions isLetter(str) {
return str.match("^[a-zA-Z()]+$");
}
函数 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
正如另一个答案所说......对不起

