Regex Replace anything but numbers and lowercase

前端 未结 4 1085
醉梦人生
醉梦人生 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: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)

提交回复
热议问题