Reputation: 460
I am tracking URLs with "posName" parameters like:
example.com?posName=Content+&+Community+Manager+(H/F)
But my code returns "Content" only:
function () {
var uri = document.location.href;
var uri_dec = decodeURIComponent(uri);
var url = new URL(uri_dec);
var posName= url.searchParams.get("posName");
return posName;
}
How can I get the full parameter?
EDIT: I have another URL like:
exemple.com?posName=Club+&+Animator+(H/F)
And the code returns the full parameter... So is it the length of the parameter which causes this issue?
Upvotes: 6
Views: 243
Reputation: 2293
If for some reason you have no control over what's in the window.location.href
, you can solve this quite easily via regex:
function getPosName(uri) {
let match = uri.match(/(?<=posName=)(.+?)(?=\&\w+?\=|$)/);
return match[1];
}
console.log(getPosName( "xemple.com?posName=Content+&+Community+Manager+(H/F)")); //Content+&+Community+Manager+(H/F)
console.log(getPosName( "exemple.com?posName=Club+&+Animator+(H/F)")); //Club+&+Animator+(H/F)
console.log(getPosName( "exemple.com?posName=Club+&+Animator+(H/F)&test=1")); // Club+&+Animator+(H/F)
Regex explanation:
(?=postName=)
lookbehind to findpostName=
to start the match
(.+?)
matches anything up to the lookahead pattern below
(?=\&\w+?\=|$)
loohahead pattern for literal&
followed by some text of any length from 1 onwards\w+?
followed by=
. All that, or we're at the end of the input string, denoted by$
Update
The regex lookbehind is relatively new. If the browser or app doesn't support the regex lookbehind (e.g. Google Tag Manager currently), try this workaround instead:
function getPosName(uri) {
let match = uri.match(/posName=(.+?)(?=\&\w+?\=|$)/);
return match[1];
}
console.log(getPosName( "xemple.com?posName=Content+&+Community+Manager+(H/F)")); //Content+&+Community+Manager+(H/F)
console.log(getPosName( "exemple.com?posName=Club+&+Animator+(H/F)")); //Club+&+Animator+(H/F)
console.log(getPosName( "exemple.com?posName=Club+&+Animator+(H/F)&test=1")); // Club+&+Animator+(H/F)
Upvotes: 1
Reputation: 1817
I've modified your function to accept the URI as an argument. You need to encode the parameter before appending it to the query string (we can't see this code here). The decodeURIComponent in your function is also not necessary.
function getPosName (URI) {
//var uri_dec = decodeURIComponent(uri);
var url = new URL(URI);
var posName = url.searchParams.get("posName");
return posName;
}
console.log("Using your current URI:", getPosName("http://exemple.com?posName=Content+&+Community+Manager+(H/F)"))
const encodedParam = encodeURIComponent("Content & Community Manager (H/F)")
console.log("Encoded Parameter:", encodedParam)
const wellFormedURI = `http://exemple.com?posName=${encodedParam}`
console.log("Well Formed URI:", wellFormedURI)
console.log("Using well formed URI:", getPosName(wellFormedURI))
Upvotes: 5