Home > Blockchain >  Fetching URL parameter and getting regex value in sessionStorage
Fetching URL parameter and getting regex value in sessionStorage

Time:10-13

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?utm_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?utm_source=criteo' and I also don't need anything before the 'promoCode' value.

Thank you so much :)

CodePudding user response:

var url = window.location.search;
var n = new URLSearchParams(url);
var o = Object.fromEntries(n.entries());
var w = o.promoCode.split("/")[0]
var s = w.replace("content","");
var s = w.replace("state","");
sessionStorage.setItem("promo_code", (s));
console.log(s)

CodePudding user response:

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?utm_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)

  • Related