Search code examples
javascriptindexingsubstring

Grab substring after and before two specific characters in javascript


i have a url search key like that: ?retailerKey=A and i want to grab the retailerKey substring. All examples that i saw are having as example how to take before the char with the indexOf example. How can i implement this to have this substring from the string ?retailerKey=A


Solution

  • You could split() the string on any ? or = and take the middle item ([1]) from the outcome array.

    const data = "?retailerKey=A";
    const result = data.split(/[\?=]/)[1];
    
    console.log(result);

    If you have multiple params, creating an object fromEntries() would be interesting.

    const data = "?retailerKey=A?otherKey=B";
    
    const keyVals = data.split(/[\?=]/).filter(x => x); // keys and values
    const result = Object.fromEntries(keyVals.reduce((acc, val, i) => {
      // create entries
      const chunkI = Math.floor(i / 2);
      if (!acc[chunkI]) acc[chunkI] = [];
      acc[chunkI].push(val);
      return acc;
    }, []));
    
    console.log(result);