0

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.

rrk
  • 15,677
  • 4
  • 29
  • 45
Graeme Bryson
  • 193
  • 4
  • 19
  • 1
    How do UK postcodes work for those not familiar with them? What sort of input are you expecting, and what should happen if the user provides unexpected input? – ggorlen May 23 '19 at 16:06
  • Well, it failed before I got halfway through - the "outward code" (before the space) can have 2 digits - yours splits between them, eg "RH10" -> "RH1 0" https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom (scroll down to Formatting section) – freedomn-m May 23 '19 at 16:06
  • You're not removing existing spaces that have already been added for one thing. Additionally, why is your second capture group looking for a digit, rather than 3 characters – Nick is tired May 23 '19 at 16:07
  • @freedomn-m All UK postcodes end in 3 characters after a space, regardless of how many are in the initial block, hence why I'm trying to place the space there – Graeme Bryson May 23 '19 at 16:08
  • Maybe, but that's not what your regex does, maybe something like `(.*)(.{3})`? – freedomn-m May 23 '19 at 16:09
  • Related https://stackoverflow.com/questions/164979/regex-for-matching-uk-postcodes – freedomn-m May 23 '19 at 16:09

0 Answers0