jQuery: Check if special characters exists in string

后端 未结 4 808
心在旅途
心在旅途 2020-12-02 10:09

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 specia

相关标签:
4条回答
  • 2020-12-02 10:33

    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.');
    }
    

    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.

    0 讨论(0)
  • 2020-12-02 10:40
    var specialChars = "<>@!#$%^&*()_+[]{}?:;|'\"\\,./~`-="
    var check = function(string){
        for(i = 0; i < specialChars.length;i++){
            if(string.indexOf(specialChars[i]) > -1){
                return true
            }
        }
        return false;
    }
    
    if(check($('#Search').val()) == false){
        // Code that needs to execute when none of the above is in the string
    }else{
        alert('Your search string contains illegal characters.');
    }
    
    0 讨论(0)
  • 2020-12-02 10:43

    You are checking whether the string contains all illegal characters. Change the ||s to &&s.

    0 讨论(0)
  • 2020-12-02 10:44

    You could also use the whitelist method -

    var str = $('#Search').val();
    var regex = /[^\w\s]/gi;
    
    if(regex.test(str) == true) {
        alert('Your search string contains illegal characters.');
    }
    

    The regex in this example is digits, word characters, underscores (\w) and whitespace (\s). The caret (^) indicates that we are to look for everything that is not in our regex, so look for things that are not word characters, underscores, digits and whitespace.

    0 讨论(0)
提交回复
热议问题