jQuery:检查字符串中是否存在特殊字符 [英] jQuery: Check if special characters exists in string

查看:304
本文介绍了jQuery:检查字符串中是否存在特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题在Stack上经常被问到,但我似乎无法从已发布的问题中得到直接的答案。

I know this question is asked more often here on Stack, but I can't seem to get a straight answer out of the questions already posted.

我需要检查是否所有特殊字符(除了 - )都在一个字符串中,如果是,则给用户一个警告。

I need to check if all special characters (except -) are in a string, if so, then give the user an alert.

到目前为止我所拥有的是:

What I have so far is this:

if($('#Search').val().indexOf('@') == -1 || $('#Search').val().indexOf('#') == -1 || $('#Search').val().indexOf('$') == -1 || $('#Search').val().indexOf('%') == -1 || $('#Search').val().indexOf('^') == -1 || $('#Search').val().indexOf('&') == -1 || $('#Search').val().indexOf('*') == -1 || $('#Search').val().indexOf('(') == -1 || $('#Search').val().indexOf(')') == -1 || $('#Search').val().indexOf('_') == -1 || $('#Search').val().indexOf('\'') == -1 || $('#Search').val().indexOf('\"') == -1 || $('#Search').val().indexOf('\\') == -1 || $('#Search').val().indexOf('|') == -1 || $('#Search').val().indexOf('?') == -1 || $('#Search').val().indexOf('/') == -1 || $('#Search').val().indexOf(':') == -1 || $('#Search').val().indexOf(';') == -1 || $('#Search').val().indexOf('!') == -1 || $('#Search').val().indexOf('~') == -1 || $('#Search').val().indexOf('`') == -1 || $('#Search').val().indexOf(',') == -1 || $('#Search').val().indexOf('.') == -1 || $('#Search').val().indexOf('<') == -1 || $('#Search').val().indexOf('>') == -1 || $('#Search').val().indexOf('{') == -1 || $('#Search').val().indexOf('}') == -1 || $('#Search').val().indexOf('[') == -1 || $('#Search').val().indexOf(']') == -1 || $('#Search').val().indexOf('+') == -1 || $('#Search').val().indexOf('=') == -1)
{
   // Code that needs to execute when none of the above is in the string
}
else
{
  alert('Your search string contains illegal characters.');
}

但这似乎不起作用...任何人都可以帮助我这件事?

But this doesn't seem to work... Can anyone help me on this matter?

提前致谢!

Guido

推荐答案

如果你真的想检查所有这些特殊字符,那么使用正则表达式会更容易:

If you really want to check for all those special characters, it's easier to use a regular expression:

var str = $('#Search').val();
if(/^[a-zA-Z0-9- ]*$/.test(str) == false) {
    alert('Your search string contains illegal characters.');
}

上述内容仅允许字符串完全由字符组成 az AZ 0-9 ,加上连字符空格字符。包含任何其他字符的字符串将导致警报

The above will only allow strings consisting entirely of characters on the ranges a-z, A-Z, 0-9, plus the hyphen an space characters. A string containing any other character will cause the alert.

这篇关于jQuery:检查字符串中是否存在特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆