SB2055 SB2055 - 1 year ago 70
jQuery Question

Regex to force dashes not working

I'm attempting to format a number as follows:


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

However it's not working as I'd expect - I just get chunks of 6:

What am I doing wrong?

Answer Source

If you can support IE9+ I would recommend using the input event. If that's not the case, you should use a library. Input Mask looks pretty good.

$('form input').on('input', function(e) {
  // get just the number
  var numeric = this.value.replace(/-/g, '');
  // split it by number of numeric characters
  split = numeric.match(/^(\d{0,6})(\d{0,2})(\d{0,4})/);
  // shift off the whole match
  // join back up using dashes and trim trailing and leading dashes
  this.value = split.join('-').replace(/^\-+|\-+$/, '');
<script src=""></script>
  <input type='text' maxlength="14"/>

Edit: if you want to get all ES6 on this thing, you can also do the following for line 9 instead of the odd regex replace.

this.value = split.filter(a=>a).join('-');