jQuery 正则表达式允许字母数字中的空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19507055/
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-27 00:07:36 来源:igfitidea点击:
Regex to allow spaces in alphanumeric
提问by Ahmed ilyas
I have this here:
我这里有这个:
$("#MyInputBox").keypress(function (e) {
if (e.charCode != 0) {
var regex = new RegExp("^[a-zA-Z0-9\-\s]+$");
var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (!regex.test(key)) {
e.preventDefault();
return false;
}
}
});
Problem is, it does not allow me to enter a space. I WANT it to allow a space. Everything else works fine (i.e I can enter numbers, letters, dash... but not a space.)
问题是,它不允许我输入空格。我希望它允许一个空间。其他一切正常(即我可以输入数字、字母、破折号……但不能输入空格。)
回答by Dr.Molle
You must escape the backslash before the s
您必须在之前转义反斜杠 s
var regex = new RegExp("^[a-zA-Z0-9\-\s]+$");
or ommit the constructor:
或省略构造函数:
var regex = /^[a-zA-Z0-9\-\s]+$/