[英]Regex to check if string contains Alphanumeric Characters and Spaces only - javascript
This is what I have so far: 这是我到目前为止:
function checkTitle(){
reg = /^[\w ]+$/;
a = reg.test($("#title").val());
console.log(a);
}
So far in my tests it catches all special characters except _
. 到目前为止,在我的测试中它捕获除_
之外的所有特殊字符。 How do I catch all special characters including _
in the current function? 如何在当前函数中捕获包括_
所有特殊字符?
I need the string to only have Alphanumeric Characters and Spaces. 我需要字符串只有字母数字字符和空格。 Appreciate the help cause I am having a hard time understanding regex patterns. 欣赏帮助因为我很难理解正则表达式模式。
Thanks! 谢谢!
Your problem is that \\w
matches all alphanumeric values and underscore. 您的问题是\\w
匹配所有字母数字值和下划线。
Rather than parsing the entire string, I'd just look for any unwanted characters. 我只是寻找任何不需要的字符,而不是解析整个字符串。 For example 例如
var reg = /[^A-Za-z0-9 ]/;
If the result of reg.test
is true
, then the string fails validation. 如果reg.test
的结果为true
,则字符串验证失败。
Since you are stating you are new to RegExp, I might as well include some tips with the answer. 既然你说你是RegExp的新手,我不妨在答案中加入一些提示。 I suggest the following regexp: 我建议以下正则表达式:
/^[a-z\d ]+$/i
Here: 这里:
i
flag in the end, which matches in a case-insensitive manner 由于最后的i
标志,不需要大写字母AZ,它以不区分大小写的方式匹配
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.