skip to Main Content

I have this string:

const inputString = 'Crew: CAP(X): Ches, Ben, FO: Smith, Matthew, FO(T,P): Singh, Sushant';

I want to split this string so that the output is like so:

[
  'Crew',
  'CAP(X): Ches, Ben, ',
  'FO: Smith, Matthew, ',
  'FO(T,P): Singh, Sushant'
]

So split but take the text immediately before.

I tried this:

const result = inputString.split(/(?<=: )/);
console.log(result);

2

Answers


  1. You can split it by space, then loop over it,
    if contains :, push a new item, otherwise just concatenate it.

    Something like below,

    const inputString = 'Crew: CAP(X): Ches, Ben, FO: Smith, Matthew, FO(T,P): Singh, Sushant'
    
    // split by space
    const words = inputString.split(/s/)
    
    let output = []
    let res = ''
    
    for (const word of words) {
        if (word.includes(':')) {
            // add new item to output if : is found and reset res
            if ( res !== '' ) 
                output.push(res)
            res = word
        } else {
            //concatenate with current res
            res += ' ' + word
        }
    }
    
    // push the last res
    output.push( res )
    
    console.log( output )
    Login or Signup to reply.
  2. This is a tricky one due to "Crew" not being the same as the rest of the string, plus all the additional commas and colons. Here’s my attempt:

    const inputString = 'Crew: CAP(X): Ches, Ben, FO: Smith, Matthew, FO(T,P): Singh, Sushant';
    
    //"Crew' is the outlier, so let's remove it for now and let's split on spaces
    let formattedString = inputString.replace("Crew: ","").split(" ");
    
    //We'll start with "Crew"
    const finalOutput = ["Crew"];
    
    let idx = 0;
    formattedString.forEach(
        fs => {
        //":" indicates title, so we'll make this into a new item in the array by increasing idx and initializing the array item at this index
        if (fs.includes(":")) {
          idx++;
          finalOutput[idx] = "";
        }
    
            //add the current word at this array index
        finalOutput[idx] += fs;
        
      }
    );
    //console.log(finalOutput)
    //add the spaces back to the colons and strings
    finalFinalOutput = finalOutput.map(
        i => i.replaceAll(":",": ").replaceAll(",",", ")
    );
    
    console.log(finalFinalOutput)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search