Regex Replace anything but numbers and lowercase

前端 未结 4 1056
醉梦人生
醉梦人生 2021-01-18 23:29

I have an input which I am binding to keyup()

On each keyup, I want it to:

  1. disallow any characters that are not a number, a letter, or a dash, and
相关标签:
4条回答
  • 2021-01-19 00:06
    this.value = this.value.toLowerCase().replace(/[^0-9a-z-]/g,"");
    
    0 讨论(0)
  • 2021-01-19 00:12
    $('.my-input').keyup(function() {
        this.value = this.value.replace(/[^0-9a-zA-Z-]/g, '').toLowerCase();
    });
    
    0 讨论(0)
  • 2021-01-19 00:16

    Good question.. you're almost there!

    $('.my-input').keyup(function() { this.value = this.value.replace(/[^A-Za-z0-9-]/g,"").toLowerCase();
    

    Regex is not the right tool for lowercasing, use the built-in function. Your regex was good, but the replace function takes one regex and the replacement is a string, not a regex*.

    (*replacement strings have some minor magic, but not enough for lowercasing)

    0 讨论(0)
  • 2021-01-19 00:18

    The regex for a number, letter or dash is: [-0-9a-z] (to include a literal dash in your character class, specify it as the first character; thereafter it's considered a range operator).

    Try:

    $('.my-input').keyup(function() {this.value = this.value.toLowerCase().replace(/[^-0-9a-z]/g,''); });
    
    0 讨论(0)
提交回复
热议问题