I'm really new in JavaScript and I would like to add to my input text, space insertion for IBAN account registering.
<input type="text" name="iban" onkeyup="if(this.value.length > 34){this.value=this.value.substr(0, 34);}" />
There is my input field; could someone tell me how I can do this?
CSS text-indent For example, to add an indent of 4 spaces, apply the rule text-indent: 4em; to the element.
To add a space between characters of a string, call the split() method on the string to get a character array, then call the join() method on the array to join the characters with a space separator.
To insert a character after every N characters, call the replace() method on the string, passing it the following regular expression - str. replace(/. {2}/g, '$&c') . The replace method will replace every 2 characters with the characters plus the provided replacement.
The existing answers are relatively long, and they look like over-kill. Plus they don't work completely (for instance, one issue is that you can't edit previous characters).
For those interested, according to Wikipedia:
Permitted IBAN characters are the digits 0 to 9 and the 26 upper-case Latin alphabetic characters A to Z.
Here is a relatively short version that is similar to the existing answers:
document.getElementById('iban').addEventListener('input', function (e) { e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim(); });
<label for="iban">iban</label> <input id="iban" type="text" name="iban" />
As stated above, the caveat is that you can't go back and edit previous characters. If you want to fix this, you would need to retrieve the caret's current position by initially accessing the selectionEnd
property and then setting the caret's position after the regex formatting has been applied.
document.getElementById('iban').addEventListener('input', function (e) { var target = e.target, position = target.selectionEnd, length = target.value.length; target.value = target.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim(); target.selectionEnd = position += ((target.value.charAt(position - 1) === ' ' && target.value.charAt(length - 1) === ' ' && length !== target.value.length) ? 1 : 0); });
<label for="iban">iban</label> <input id="iban" type="text" name="iban" />
You will notice that there is a slight issue when the character after the caret is a space (because the space wasn't accounted for when initially retrieving the caret's position to begin with). To fix this, the position is manually incremented if the succeeding character is a space (assuming a space was actually added - which is determined by comparing the length before and after replacing the characters).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With