Regex Replace everything except numbers and lowercase letters

I have an input that I associate with keyup ()

In every keyboard I want:

  • prohibit any characters that are not a number, letter or dash, and
  • replace any uppercase letters with lowercase letters.

Regex makes my head explode, any help?

$('.my-input').keyup(function() { this.value = this.value.replace(/[^0-9a-z-]/g,/[0-9a-z-]/g); }); 
+4
source share
4 answers
 this.value = this.value.toLowerCase().replace(/[^0-9a-z-]/g,""); 
+13
source
 $('.my-input').keyup(function() { this.value = this.value.replace(/[^0-9a-zA-Z-]/g, '').toLowerCase(); }); 
+1
source

The regular expression 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, after which it will consider the range operator).

Try:

 $('.my-input').keyup(function() {this.value = this.value.toLowerCase().replace(/[^-0-9a-z]/g,''); }); 
+1
source

Good question .. are you almost there!

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

Regex is not the most suitable tool for the bottom, use the built-in function. Your regex was good, but the replace function accepts one regex, and the replacement is a string, not a regex *.

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

0
source

All Articles