Search code examples
javascriptstringfunctionspacing

How do I create a function that extracts the middle to end of strings of different lengths?


I am trying to make a function that adds a space between "flight" and "###" but would like to make it work if the flight number is greater than 3 digits. I know I could make the second part of the slice method a huge number and it would technically work but I figure there should be a more elegant way. Any help would be appreciated, thanks!

const addSpace = function (str) {
      const flightNumber = str.slice(6, 9);
      return [str.slice(0, 6) + ' ' + flightNumber]
    }
    
    console.log(...addSpace('flight843'));

Solution

  • As flight string will always be there. We can simply achieve this by using String.replace() method. I also done the performance test in jsbench and it runs fastest among all the solutions mentioned here.

    Live Demo :

    const addSpace = function (str) {
      const len = str.replace('flight', '').length;
      return len > 3 ? str.replace('flight', 'flight ') : str
    }
    
    console.log(addSpace('flight843')); // 'flight843'
    console.log(addSpace('flight8432')); // 'flight 8432'