title: Plain Javascript way to add a space on the fly after every 5th digit in input field
body: <p>How can I add a space after every 5th number (as the user types) in input field? </p>
  
  <p>12345 56789 12345 56789</p>
  
  <p>The limitation is that I cannot use any framework like jQuery.  This has to be done using plain Javascript or CSS.  </p>
  
  <p>I also need to support the ability to hit backspace and correct the number or place cursor anywhere and start correcting with backspace.</p>
  
  <p>The following code is based on the answer here:
  <a href="https://stackoverflow.com/questions/17260238/how-to-insert-space-every-4-characters-for-iban-registering">How to insert space every 4 characters for IBAN registering?</a></p>
  
  <p><strong>The backspace does not work reliably.</strong></p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function space(str, after) {
    if (!str) {
      return false;
    }
    after = after || 4;
    var v = str.replace(/[^\dA-Z]/g, ''),
      reg = new RegExp(".{" + after + "}", "g");
    return v.replace(reg, function(a) {
      return a + ' ';
    });
  }
  
  var el = document.getElementById('pin');
  el.addEventListener('keyup', function() {
    this.value = space(this.value, 4);
  });</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form&gt;
    &lt;input autocapitalize="off" autocorrect="off" maxlength=20 type="text" placeholder="type the pin" id="pin" name="pin" /&gt;
    &lt;script&gt;
    &lt;/script&gt;
  &lt;/form&gt;</code></pre>
  </div>
  </div>
  </p>