I have an input which I am binding to keyup()
On each keyup, I want it to:
- disallow any characters that are not a number, a letter, or a dash, and
- replace any uppercase characters with lowercase ones.
Regex makes my head explode, any help?
$('.my-input').keyup(function() {
this.value = this.value.replace(/[^0-9a-z-]/g,/[0-9a-z-]/g);
});
I have an input which I am binding to keyup()
On each keyup, I want it to:
- disallow any characters that are not a number, a letter, or a dash, and
- replace any uppercase characters with lowercase ones.
Regex makes my head explode, any help?
$('.my-input').keyup(function() {
this.value = this.value.replace(/[^0-9a-z-]/g,/[0-9a-z-]/g);
});
Share
Improve this question
edited Dec 15, 2011 at 5:08
Dave M
1,3221 gold badge16 silver badges28 bronze badges
asked May 27, 2011 at 3:06
wesboswesbos
26.3k31 gold badges108 silver badges144 bronze badges
1
- 1 You've already got help with the RegEx part of this, but don't forget that users can enter data in your input without triggering the keyup event if they do it with the mouse (right-click and paste, drag'n'drop). – nnnnnn Commented May 27, 2011 at 3:21
4 Answers
Reset to default 14this.value = this.value.toLowerCase().replace(/[^0-9a-z-]/g,"");
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,''); });
$('.my-input').keyup(function() {
this.value = this.value.replace(/[^0-9a-zA-Z-]/g, '').toLowerCase();
});
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)