Quantcast
Channel: Reformat string containing uk postcode using regex - Stack Overflow
Viewing all articles
Browse latest Browse all 4

Answer by ShrapNull for Reformat string containing uk postcode using regex

$
0
0

I've used the excellent answer from @borodin above to create a UK postcode as-you-type formatter. Note, this does not validate the postcode, just formats it according to borodin's regex as the user types.

var txtPc = $("#postcode");var outputCount = 0;var jigCount = 0;var postcodePauseTime = 500;txtPc.on("keydown", function(e) {  var keyCode = e.which;  var key = String.fromCharCode(keyCode);  var isAlphaNumeric = //key.match(/^[a-z0-9]+$/i);    (      (keyCode >= 65 && keyCode <= 90) ||      (keyCode >= 48 && keyCode <= 57) ||      ([189, 190, 8, 46, 9].indexOf(keyCode) > -1) ||      (keyCode >= 35 && keyCode <= 40)    );  return !!isAlphaNumeric;});// handle click and add classtxtPc.on("keyup", function(e) {  PostcodeCalculateFormat(txtPc);});txtPc.on("blur", function() {  PostcodeCalculateFormat(txtPc);});function PostcodeCalculateFormat(txtPc) {  (function(index, txtPc) {    setTimeout(function() {      //prevent interferance from other keypresses by returning out of this closure      if (index != jigCount) return;      var isFocused = ($('#'+ txtPc.attr('id') +':focus')[0] == document.activeElement);      var postcodeText = txtPc.val().toUpperCase(); /// + key;      var origSpacePos = postcodeText.indexOf("");      postcodeText = postcodeText.replace(/[\W_]+/g, "");      var parts = postcodeText.match(/^([A-Z]{1,2}\d{1,2}[A-Z]?)\s*(\d[A-Z]{2})$/i);      //if unable to match the lot, try the first part only with less strict reg      if (!parts)        parts = postcodeText.match(/^([A-Z]{1,2}\d{1,2}[A-Z]?)\s*(.*)$/i);      if (parts) {        var caretPos = 0;        if (isFocused)          caretPos = getCaretPosition(txtPc[0]).start;        parts.shift();        var newVal = parts.join('');        if (newVal == txtPc.val())          return;        output(newVal);        txtPc.val(newVal);        var spacePos = newVal.indexOf("");        if (isFocused) {          if (caretPos >= spacePos && origSpacePos == -1)            caretPos++;          setCaretPosition(txtPc[0], caretPos, caretPos);        }      }    }, postcodePauseTime);  }(++jigCount, txtPc));}function output(str) {  $("#listOutput").prepend("<li>["+ (++outputCount) +"] "+ str +"</li>");}function getCaretPosition(ctrl) {  // IE < 9 Support  if (document.selection) {    ctrl.focus();    var range = document.selection.createRange();    var rangelen = range.text.length;    range.moveStart('character', -ctrl.value.length);    var start = range.text.length - rangelen;    return {'start': start,'end': start + rangelen    };  }  // IE >=9 and other browsers  else if (ctrl.selectionStart || ctrl.selectionStart == '0') {    return {'start': ctrl.selectionStart,'end': ctrl.selectionEnd    };  } else {    return {'start': 0,'end': 0    };  }}function setCaretPosition(ctrl, start, end) {  // IE >= 9 and other browsers  if (ctrl.setSelectionRange) {    ctrl.focus();    ctrl.setSelectionRange(start, end);  }  // IE < 9  else if (ctrl.createTextRange) {    var range = ctrl.createTextRange();    range.collapse(true);    range.moveEnd('character', end);    range.moveStart('character', start);    range.select();  }}
body {  background: silver;  padding: 20px;  font-family: Helvetica;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script><div>Sample postcodes to type: 'BT92PE', 'EC1A3AD', 'GU348RR', 'N13LD'</div><div>  Postcode: <input id="postcode" style="text-transform: uppercase; " /></div><!-- for troubleshooting --><ul id="listOutput"></ul>

The caret get & set functions were taken straight from a stack overflow answer, which I can't find right now to give the user credit. I will look & update with a link if I can.

This does everything I want it to, but it's not a very elegant solution. I'm happy for somebody out there to revamp, enhance or improve on this. I'd like to see the result.

Improvement for future: if the caret is after the space, the backspace key should remove the space AND the alphanumeric character before it in one key press. (same idea for the delete button if the caret is in before the space.)


Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>