在 Javascript 中,如何检查字符串是否仅为字母 + 数字(允许下划线)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8253189/
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
In Javascript, how do I check if string is only letters+numbers (underscore allowed)?
提问by TIMEX
How do I check that?
我如何检查?
I want to allow all A-Za-z0-9 , and underscore. Any other symbol, the function should return false.
我想允许所有 A-Za-z0-9 和下划线。任何其他符号,该函数应返回 false。
回答by Tikhon Jelvis
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_]
. If you want the empty string to return true
, change the +
to a *
.
\w
是一个字符类,它完全代表您想要的内容:[A-Za-z0-9_]
. 如果您希望返回空字符串true
,请将 更改+
为 a *
。
To help you remember it, the \w
is a w
ord character. (It turns out that words have underscores in JavaScript land.)
为了帮助您记住它,这\w
是一个w
ord 字符。(事实证明,在 JavaScript 领域,单词有下划线。)
回答by ioseb
I think this is a solution:
我认为这是一个解决方案:
function check(input) {
return /^\w+$/i.test(input);
}