I am trying to format an <input>
box using javascript / jquery.
The Goal - As the user types, add hyphens automatically after every third character.
123123123 becomes 123-123-123
I have a working code, but it is super slow and clunky. I am looking for recommendations on how to improve the code
$('#serial').keyup(function(){
$(this).val( $(this).val().trim() );
var str = $(this).val();
var newStr = str.replace(/-/g, "");
var valuesArray = newStr.split("");
var newVal = "";
while ( i = valuesArray.shift() ){
if(newVal.length === 3){
newVal += "-";
} else if (newVal.length === 7){
newVal += "-";
}
newVal += i;
}
$(this).val(newVal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<label for="serial">Type something magical</label>
<input type="text" id="serial" name="serial">