0

I found a pretty old example but it's almost doing exactly what i need to do: Auto Dash using Javascript on FOCUS (for a telephone number format)

However instead of the current format xxx-xxx-xxxx i'd like to do (xxx) xxx-xxxx

Can someone give me a hand with the script below with this??

$('.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, '');

    console.log("this value", this.value);
});
Community
  • 1
  • 1
doubleya
  • 479
  • 9
  • 17

3 Answers3

2

You could do something like this

var a = this.value.match(/\d*/g).join('')
        .match(/(\d{0,3})(\d{0,3})(\d{0,4})/).slice(1);

this.value  = ['(',a[0],') ',a[1],'-',a[2]].join('');

It's not very elegant but hey, elegance is for tailors right?

Update

Yea, I got bored and made a one-liner, here:

this.value =  '('+this.value
        .match(/\d*/g).join('')
        .match(/(\d{0,3})(\d{0,3})(\d{0,4})/).slice(1)
        .map((a,i)=>(a+[') ','-',''][i])).join(''); 
Joe Thomas
  • 5,807
  • 6
  • 25
  • 36
0

The code you'll want to change is .join('-'). That's where you're getting the 'xxx-xxx-xxxx' from.

robrich
  • 13,017
  • 7
  • 36
  • 63
0

You need to tokenize those 3 regular expressions and then join them separately.