SB2055 SB2055 - 2 months ago 19
jQuery Question

Regex to force dashes not working

I'm attempting to format a number as follows:

123456-12-1234
:

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


However it's not working as I'd expect - I just get chunks of 6: http://jsfiddle.net/juspC/892/

What am I doing wrong?

Answer

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
  split.shift();
  // join back up using dashes and trim trailing and leading dashes
  this.value = split.join('-').replace(/^\-+|\-+$/, '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type='text' maxlength="14"/>
</form>

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