I'm looking at auto populating hyphen's are irregular lengths for an HTML input field.
After the 2nd digit/character
After the 6th digit/character
After the 13th digit/character
12-3456-7891234-00000
I've come up with the below code which works fine at adding the hyphen's. Using backspace however is destroying the logic. Is there anyway I can achieve this using regex perhaps where it considers the entire string to process the split ?
var newFoo = '';
$('.nzPhoneNumber').on('change keydown paste input', function(){
var foo = $(this).val();
if (foo.length === 2) {
newFoo = foo.concat('-')
$(this).val(newFoo);
} else if (foo.length === 7) {
newFoo = newFoo + foo.substring(3,7) + '-'
$(this).val(newFoo);
} else if (foo.length === 15) {
newFoo = newFoo + foo.substring(8,15) + '-'
$(this).val(newFoo);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="nzPhoneNumber" />