I’m trying to format postcode entries in a form correctly so that they have a space in the correct location, which is always three characters from the end. E.g.:
AA1 1AA
A1A 1AA
AA11 1AA
A1 1AA
const addSpace = (str, fromEnd) => `${str.slice(0, -1 * fromEnd)} ${str.slice(-1 * fromEnd)}`; ['word', 'longword'].forEach(word => console.log(addSpace(word, 3))); var el = document.getElementById('input_1_14'); el.addEventListener('keyup', function () { this.value = addSpace(this.value, 3); });
However, if I type a series of characters into the relevant field it is inserting spaces every other character, in addition to one three characters from the end, e.g.:
1 1 1 1 1 1 111
Where am I going wrong?
Advertisement
Answer
It is becous of the event onKeyUp
, you place an extra letter and it keeps adding spaces after every event without removing them.
const addSpace = (str, fromEnd) => `${str.slice(0, -1 * fromEnd)} ${str.slice(-1 * fromEnd)}`; const removeSpace = (str) => str.replace(/ /g, ""); const editString = (str, fromEnd) => addSpace(removeSpace(str), fromEnd); ['word', 'longword'].forEach(word => console.log(editString(word, 3))); var el = document.getElementById('input_1_14'); el.addEventListener('keyup', function () { this.value = editString(this.value, 3); });
<input type="tex" id="input_1_14">