Search code examples
javascriptconsole.logsession-storagegoogle-developers-console

Fetching URL parameter and getting regex value in sessionStorage


Trying to figure this out and was hoping someone here can help. Trying to make a JavaScipt that can capture the 'promoCode' parameter without the parameter name and all the junk behind it (other values after the parameter value), and then stores the results in sessionStorage.

Here's an example URL:

https://www.constellation.com/solutions/for-your-home/residential-signup.html?zip=77493&promoCode=rockstarcontent/constellation/en/campaigns/DisplayNew2020.html%3futm_source=criteo

This is what I want the result to be: 'rockstar'

Notice how I don't want this section 'content/constellation/en/campaigns/DisplayNew2020.html%3futm_source=criteo' and I also don't need anything before the 'promoCode' value.

Thank you so much :)


Solution

  • Without regex. If you know that it is always on the same position (first in this case) you can use this approach:

    const url = 'https://www.constellation.com/solutions/for-your-home/residential-signup.html?zip=77493&promoCode=rockstarcontent/constellation/en/campaigns/DisplayNew2020.html%3futm_source=criteo' 
    
    const n = new URLSearchParams(url);
    const o = Object.fromEntries(n.entries());
    const w = o.promoCode.split("/")[0]
    
    const s = w.replace("content","");
    
    console.log(s)