最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regex Replace anything but numbers and lowercase - Stack Overflow

programmeradmin0浏览0评论

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
  2. 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:

  1. disallow any characters that are not a number, a letter, or a dash, and
  2. 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
Add a comment  | 

4 Answers 4

Reset to default 14
this.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)

发布评论

评论列表(0)

  1. 暂无评论