javascript code to check special characters

后端 未结 6 1739
后悔当初
后悔当初 2020-12-08 10:45

I have JavaScript code to check if special characters are in a string. The code works fine in Firefox, but not in Chrome. In Chrome, even if the string does not contain spec

相关标签:
6条回答
  • 2020-12-08 11:04

    You could also do it this way.

    specialRegex = /[^A-Z a-z0-9]/ specialRegex.test('test!') // evaluates to true Because if its not a capital letter, lowercase letter, number, or space, it could only be a special character

    0 讨论(0)
  • 2020-12-08 11:10

    You can test a string using this regular expression:

    function isValid(str){
     return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
    }
    
    0 讨论(0)
  • 2020-12-08 11:14

    Directly from the w3schools website:

       var str = "The best things in life are free";
       var patt = new RegExp("e");
       var res = patt.test(str);
    

    To combine their example with a regular expression, you could do the following:

    function checkUserName() {
        var username = document.getElementsByName("username").value;
        var pattern = new RegExp(/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/); //unacceptable chars
        if (pattern.test(username)) {
            alert("Please only use standard alphanumerics");
            return false;
        }
        return true; //good user input
    }
    
    0 讨论(0)
  • 2020-12-08 11:15

    Did you write return true somewhere? You should have written it, otherwise function returns nothing and program may think that it's false, too.

    function isValid(str) {
        var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
    
        for (var i = 0; i < str.length; i++) {
           if (iChars.indexOf(str.charAt(i)) != -1) {
               alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
               return false;
           }
        }
        return true;
    }
    

    I tried this in my chrome console and it worked well.

    0 讨论(0)
  • 2020-12-08 11:17

    Try This one.

    function containsSpecialCharacters(str){
        var regex = /[ !@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/g;
    	return regex.test(str);
    }

    0 讨论(0)
  • 2020-12-08 11:20

    If you don't want to include any special character, then try this much simple way for checking special characters using RegExp \W Metacharacter.

    var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
    if(!(iChars.match(/\W/g)) == "") {
        alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
        return false;
    }
    
    0 讨论(0)
提交回复
热议问题