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.
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, '')
;
});
foo = foo.match(new RegExp('.{1,4}$|.{1,3}', 'g')).join("-");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With