jQuery: Check if special characters exists in string

后端 未结 4 904
心在旅途
心在旅途 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: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.

提交回复
热议问题