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

Time:07-14

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'));

CodePudding user response:

You can match 6 characters a-z and 3 or more digits using a pattern with 2 capture groups.

In the replacement use the 2 capture groups with a space in between.

const addSpace = str => str.replace(/\b([a-z]{6})(\d{3,})\b/g, "$1 $2");
console.log(addSpace('flight843'));

You can also literally match flight, and append anchors if that is the only allowed string.

^(flight)(\d{3,})$

CodePudding user response:

If you need only addSpace I belived this is a simple solution for your quest. With this dynamic function is possible add Space for many block of words.

/* ADD Spacing */

 const string = "flightNumber";
 const dataValue = "flight";

 function addSpacing(str, data){

    //Verify if exist the wolrd in the string

    if(str.includes(data)){

        //get the word
        let word = str.substr(0, data.length);

        //Add Capitalise
        let strCapitalize = word.charAt(0).toUpperCase();

        let cleanword = word.slice(1,  data.length);

        //add spacing
        let newStr = str.replace(word, strCapitalize   cleanword   " ");
        
        console.log(newStr);

    }

 }

 addSpacing(string, dataValue);
  • Related