[英]In Javascript, how do I check if string is only letters+numbers (underscore allowed)?
How do I check that? 我该如何检查?
I want to allow all A-Za-z0-9 , and underscore. 我想允许所有A-Za-z0-9和下划线。 Any other symbol, the function should return false.
任何其他符号,该函数应返回false。
You can use a regular expression: 您可以使用正则表达式:
function isValid(str) { return /^\w+$/.test(str); }
\\w
is a character class that represents exactly what you want: [A-Za-z0-9_]
. \\w
是一个完全代表你想要的字符类: [A-Za-z0-9_]
。 If you want the empty string to return true
, change the +
to a *
. 如果希望空字符串返回
true
,请将+
更改为*
。
To help you remember it, the \\w
is a w
ord character. 为了帮助你记住它,
\\w
是一个w
ord角色。 (It turns out that words have underscores in JavaScript land.) (事实证明,单词在JavaScript中有下划线。)
I think this is a solution: 我认为这是一个解决方案:
function check(input) {
return /^\w+$/i.test(input);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.