I have the English postal codes have the format X1 1XX
, XX1 1XX
or XX11 1XX
And they come to me together, so X11XX
, XX11XX
and XX111XX
. And I need to show with the spaced format.
Then the issue is that I need to put a space in the position string.length -3
addr = 'T11DH';
addr = (addr).slice(0, 2) + " " + (addr).slice(2);
console.log(addr)
addr = 'TN11DH';
addr = (addr).slice(0, 3) + " " + (addr).slice(3);
console.log(addr)
addr = 'TN131DH';
addr = (addr).slice(0, 4) + " " + (addr).slice(4);
console.log(addr)
As you can see, if I do slice
, I need to change the size that I need to cut depending on the length of the string.
switch(addr.length){
case 5:
addr = (addr).slice(0, 2) + " " + (addr).slice(2);
break;
case 6:
addr = (addr).slice(0, 3) + " " + (addr).slice(3);
break;
case 7:
addr = (addr).slice(0, 4) + " " + (addr).slice(4);
break;
}
I think it's too much code, and that there has to be a more efficient way. But I can not think of any.