Javascript 只有空格和字母的正则表达式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12778083/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:14:16  来源:igfitidea点击:

regex with space and letters only?

javascriptjquery

提问by Aoi M. Serizawa

I made a regular expression that only accepts letters. I'm not really good in regex, thats why I don't know how to include spaces in my regex.

我做了一个只接受字母的正则表达式。我不太擅长正则表达式,这就是为什么我不知道如何在正则表达式中包含空格。

My HTML:

我的 HTML:

<input id="input" />

My js / jQuery code:

我的 js/jQuery 代码:

$('#input').on('keyup', function() {
      var RegExpression = /^[a-zA-Z]*$/; 

      if (RegExpression.test($('#input').val())) {

      } 
      else {
          $('#input').val("");
      }
});?

回答by Pragnesh Chauhan

use this expression

使用这个表达

var RegExpression = /^[a-zA-Z\s]*$/;  

for more refer this http://tools.netshiftmedia.com

有关更多信息,请参阅http://tools.netshiftmedia.com

回答by Fabrizio Calderan

$('#input').on('keyup', function() {
     var RegExpression = /^[a-zA-Z\s]*$/;  
     ...

});

\swill allow the space

\s将允许空间

回答by Tats_innit

Try this demo please: http://jsfiddle.net/sgpw2/

请尝试这个演示:http: //jsfiddle.net/sgpw2/

Thanks Jan for spaces \srest there is some good detail in this link:

感谢 Jan 的空间\s休息,此链接中有一些很好的细节:

http://www.jquery4u.com/syntax/jquery-basic-regex-selector-examples/#.UHKS5UIihlI

http://www.jquery4u.com/syntax/jquery-basic-regex-selector-examples/#.UHKS5UIihlI

Hope it fits your need :)

希望它适合您的需要 :)

code

代码

 $(function() {

    $("#field").bind("keyup", function(event) {
        var regex = /^[a-zA-Z\s]+$/;
        if (regex.test($("#field").val())) {
            $('.validation').html('valid');
        } else {
            $('.validation').html("FAIL regex");
        }
    });
});?

回答by Jayant Muthekar

Allowed only characters & spaces. Ex : Jayant Lonari

只允许字符和空格。前任 :Jayant Lonari

if (!/^[a-zA-Z\s]+$/.test(NAME)) {
    //Throw Error
}