I'm trying to force input formatting (live, hence the keyup
event) with a space before the third last character of a UK postcode. I have an existing function which works with a pasted value, but not on live input (when typing, multiple spaces are being placed). I've browsed a couple of similar questions, but haven't come across any which cover formatting the input as it's being typed.
jQuery(function($) {
$("#customerPostcode").keyup(function() {
const regex = /^(.*)(\d)/g;
const str = $("#customerPostcode").val();
const subst = `$1 $2`;
const result = str.replace(regex, subst);
$("#customerPostcode").val(result);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="customerPostcode" type="text">
Live example here: https://jsfiddle.net/graemebryson/Lu3o5zw1/21/
I've made substantially more progress with this approach over previous attempts with substrings, but I'm not averse to the latter. Any advice would be massively appreciated.