javascript 检查字符串是否包含javascript中的任何特殊字符或字符串

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

checking whether a string contains any special character or string in javascript

javascriptalert

提问by Saswat

I want to check whether a string has any special characters or not. I am using this script:

我想检查一个字符串是否有任何特殊字符。我正在使用这个脚本:

var name = $("#name").val();
if(name.match(/[_\W]0-9/))
{
    alert('Not A Name');
}

It doesn't alert even when name="sas23"

即使什么时候也不会提醒 name="sas23"

回答by marekful

instead /[_\W]0-9/your regex literal should be /[_\W0-9]/

相反,/[_\W]0-9/您的正则表达式文字应该是/[_\W0-9]/

回答by Ali Issa

Your function should be like this:

你的函数应该是这样的:

var name=$("#name").val();
if(!isLetters(name))
{
   alert('Not A Name');
}
function isLetters(str) {
   return /^[a-zA-Z]+$/.test(str);
}

回答by jbabey

You should always take a whitelist approach when creating regular expressions. That means specify which characters are allowed, and ban everything else by default. If all you want is letters, then only allow letters:

创建正则表达式时,您应该始终采用白名单方法。这意味着指定允许哪些字符,并在默认情况下禁止其他所有字符。如果你想要的只是字母,那么只允许字母:

var name=$("#name").val();

if(!name.match(/^[a-z]+$/i)) {
    alert('Not A Name');
}

Try it out.

试试看。