Get key value from url
November 09, 2020
Suppose your have a url www.someexample.com?email=aditya%40rensoriginal.com&utm_campaign=VIP%20request%20US%20%28%20%2B%20no%20listed%20country%29%20%28RMd2wQ%29&utm_medium=email&utm_source=everyone%20without%20a%20country&_ke=
and you want to get the email and it’s value.
Here, I will provide two solutions for above problem, one with regex and one without regex. Let’s see the first one with regex.
function getUrlVars() {
var vars = {};
var parts = urlString.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
console.log({m})
vars[key] = value;
});
console.log({vars})
return vars;
}
Another solution without regex,
function getUrlVars() {
return urlString.split('?')[1].split('&').reduce((final, cv) => {
const [key, value] = cv.split('=')
return {
...final,
[key]: value
}
}, {})
}