jQuery only allow numbers,letters and hyphens

前端 未结 3 1680
执笔经年
执笔经年 2021-01-16 08:25

How can I remove everything but numbers,letters and hyphens from a string with jQuery?

I found this code which allows only alphanumerical characters only but I\'m no

相关标签:
3条回答
  • 2021-01-16 08:38

    You just have to change the regexp to this : "^[a-zA-Z0-9\-]+$".

    Note that the hyphen is escaped using \, otherwise it is used to specify a range like a-z (characters from a to z).

    This code will only check if the last typed character is in the allowed list, you might also want to check if after a paste in your field, the value is still correct :

    // The function you currently have
    $('#text').keypress(function (e) {
        var allowedChars = new RegExp("^[a-zA-Z0-9\-]+$");
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (allowedChars.test(str)) {
            return true;
        }
        e.preventDefault();
        return false;
    }).keyup(function() {
        // the addition, which whill check the value after a keyup (triggered by Ctrl+V)
        // We take the same regex as for allowedChars, but we add ^ after the first bracket : it means "all character BUT these"
        var forbiddenChars = new RegExp("[^a-zA-Z0-9\-]", 'g');
        if (forbiddenChars.test($(this).val())) {
            $(this).val($(this).val().replace(forbiddenChars, ''));
        }
    });
    
    0 讨论(0)
  • 2021-01-16 08:38

    I think you can just put a hyphen inside the square brackets.

    "^[a-z A-Z 0-9 -]+$"
    
    0 讨论(0)
  • 2021-01-16 09:02

    Since there is so much attention on including a hyphen within a character class amongst these answers and since I couldn't find this information readily by Googling, I thought I'd add that the hyphen doesn't need to be escaped if it's the first character in the class specification. As a result, the following character class will work as well to specify the hyphen in addition to the other characters:

    [-a-zA-Z0-9]
    
    0 讨论(0)
提交回复
热议问题