javascript code to check special characters

后端 未结 6 1741
后悔当初
后悔当初 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: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
    }
    

提交回复
热议问题