JavaScript:检查给定的字符串是否只包含字母或数字

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

JavaScript: check if a giving string contains only letters or digits

javascript

提问by senior

Using JavaScript, I wanna check if a giving string contains only letters or digits and not a special characters:

使用 JavaScript,我想检查一个给定的字符串是否只包含字母或数字而不是特殊字符:

I find this code which checks if a string contains only letters:

我发现这个代码检查字符串是否只包含字母:

    boolean onlyLetters(String str) {
      return str.match("^[a-zA-Z]+$");
    }

but my string can contain digits too. can you help me?

但我的字符串也可以包含数字。你能帮助我吗?

thanks in advance :)

提前致谢 :)

回答by bugwheels94

Add 0-9 also to your regex

将 0-9 也添加到您的正则表达式

 boolean onlyLetters(String str) {
   return str.match("^[A-Za-z0-9]+$");
 }

回答by valjeanval42

Using regexp, you can add 0-9to say any digit between 0 and 9:

使用正则表达式,您可以添加0-9表示 0 到 9 之间的任何数字:

boolean onlyLettersAndDigits(String str) {
      return str.matches("^[a-zA-Z0-9]+$");
    }