Prevent input cursor from going to end of input after value replace on keyup
<p>I'm using the function found <a href="https://stackoverflow.com/questions/27852888/put-dash-after-every-n-character-during-input-from-keyboard">here</a> for formatting an input. It works, the only problem is that when adding text to the input, the caret automatically goes to the end of the input, and doesn't allow adding anything to any other place of the input that is not the end. </p>

<p>How can I prevent the cursor/cursor from going to the end of the input on <code>keyup</code>?</p>

<pre><code>function format(input, format, sep) {
    var output = "";
    var idx = 0;
    for (var i = 0; i &lt; format.length &amp;&amp; idx &lt; input.length; i++) {
        output += input.substr(idx, format[i]);
        if (idx + format[i] &lt; input.length) output += sep;
        idx += format[i];
    }
    output += input.substr(idx);
    return output;
}

$('.phoneinput').keypress( function(e){
    var phoneLength = $(this).val();
    phoneLength = phoneLength.replace(/[^\d]/g,'').length;
    if (phoneLength == 10) { 
        e.preventDefault();
    }
});

$('.phoneinput').keyup(function(e) {
    var phoneNumber = $(this).val().replace(/-/g, "");
    if (phoneNumber.length &lt;= 10) {
        phoneNumber = format(phoneNumber, [2, 4], "-");
    }
    $(this).val(phoneNumber);
});
</code></pre>