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
JavaScript
x
7
1
const addSpace = (str, fromEnd) => `${str.slice(0, -1 * fromEnd)} ${str.slice(-1 * fromEnd)}`;
2
['word', 'longword'].forEach(word => console.log(addSpace(word, 3)));
3
var el = document.getElementById('input_1_14');
4
el.addEventListener('keyup', function () {
5
this.value = addSpace(this.value, 3);
6
});
7
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.
JavaScript
1
10
10
1
const addSpace = (str, fromEnd) => `${str.slice(0, -1 * fromEnd)} ${str.slice(-1 * fromEnd)}`;
2
const removeSpace = (str) => str.replace(/ /g, "");
3
const editString = (str, fromEnd) => addSpace(removeSpace(str), fromEnd);
4
['word', 'longword'].forEach(word => console.log(editString(word, 3)));
5
6
var el = document.getElementById('input_1_14');
7
8
el.addEventListener('keyup', function () {
9
this.value = editString(this.value, 3);
10
});
JavaScript
1
1
1
<input type="tex" id="input_1_14">