Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto Dash using Javascript on FOCUS (for a telephone number format)

Was trying to achieve, an auto dash for this format XXX-XXX-XXXX

Here's what I have so far:

$('.telnumber').keyup(function() {
  var foo = $(this).val().split("-").join(""); // remove hyphens
  foo = foo.match(new RegExp('.{1,3}', 'g')).join("-");
  $(this).val(foo);
});

First 2 blocks are fine, but How can I restrict the last block to accept 4 digits?

It's still auto dashing if there are 3 digits so far.

I'm not good at REGEX so any ideas will be appreciated.

like image 200
xirukitepe Avatar asked Oct 01 '13 09:10

xirukitepe


2 Answers

Here I think best solution. Any non digit chars will be ignored and you will not have extra dashes in the end.

$('.telnumber').keyup(function() {
    this.value = this.value
        .match(/\d*/g).join('')
        .match(/(\d{0,3})(\d{0,3})(\d{0,4})/).slice(1).join('-')
        .replace(/-*$/g, '')
    ;
});
like image 87
redexp Avatar answered Sep 30 '22 19:09

redexp


foo = foo.match(new RegExp('.{1,4}$|.{1,3}', 'g')).join("-");
like image 30
Anirudha Avatar answered Sep 30 '22 19:09

Anirudha