Javascript javascript正则表达式:只允许英文字母
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3073176/
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
javascript regex : only english letters allowed
提问by yoda
Quick question: I need to allow an input to only accept letters, from a to z and from A to Z, but can't find any expression for that. I want to use the javascript test() method.
快速问题:我需要允许输入只接受字母,从 a 到 z 和从 A 到 Z,但找不到任何表达式。我想使用 javascript test() 方法。
回答by meder omuraliev
/^[a-zA-Z]+$/.test('sfjd')
Note: If you have any punctuation marks or anything, those are all invalid too. Dashes and underscores are invalid. \wcovers a-zA-Z and some other word characters. It all depends on what you need specifically.
注意:如果你有任何标点符号或任何东西,那些也都是无效的。破折号和下划线无效。\w涵盖 a-zA-Z 和其他一些单词字符。这一切都取决于您具体需要什么。
回答by Shawn Moore
Another option is to use the case-insensitive flag i, then there's no need for the extra character range A-Z.
另一种选择是使用不区分大小写的标志 i,则不需要额外的字符范围 AZ。
var reg = /^[a-z]+$/i;
console.log( reg.test("somethingELSE") ); //true
console.log( "somethingELSE".match(reg)[0] ); //"somethingELSE"
Here's a DEMOon how this regex works with test() and match().
这是一个关于这个正则表达式如何与 test() 和 match() 一起工作的演示。

