Insert character in a text string

0

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.

    
asked by Txmx 15.08.2018 в 12:10
source

2 answers

1

string does not offer any functionality to enter a character in a specific position; just look at the API.

That said, there are always options to optimize:

  • make a function

    function arreglarCP(var addr, var posicion) {
       return addr.slice(0, posicion) + " " + (addr).slice(posicion);  
    }
    
    ....
    addr = arreglarCP(addr, 2);
    
  • the switch does not seem very necessary:

    addr = arreglarCP(addr, addr.length - 3);
    
  • Due to the restrictions of the format, it is enough to replace "11" with "1 1":

    addr = addr.replace("11", "1 1");
    

Anyway, except for the "learn to do things differently", this type of "micro-optimizations" 1 are generally not worth it.

1 No, none of this will appreciably improve the performance of your system.     
answered by 15.08.2018 / 12:36
source
0

I propose a solution with substring:

const cpFormateado = addr.substring(0, addr.length - 3)
   + ' '
   + addr.substring(addr.length - 3, addr.length);
    
answered by 15.08.2018 в 14:12