I've got the following code, so I can get parameters from a url.
However one of the parameters has a &
sign in the text resulting in the text after it being cuts off. how do I get the & sign to display with the corresponding text after it?
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
var cmp = getUrlVars()["cmp"];
document.getElementById("currentMemberPackage").value = cmp;
var replaced = cmp.replace(/%20/g, " ");
Example URL = ?Club%20Plus%20Health%20&%20Fitness
(I can't change this as it has &
in the data which is pushing through into the URL)
Displays: Club Plus Health
Should be: Club Plus Health & Fitness
The url. parse() method takes a URL string, parses it, and it will return a URL object with each part of the address as properties. Parameters: This method accepts three parameters as mentioned above and described below: urlString: It holds the URL string which needs to parse.
To identify a URL parameter, refer to the portion of the URL that comes after a question mark (?). URL parameters are made of a key and a value, separated by an equal sign (=). Multiple parameters are each then separated by an ampersand (&).
PHP | parse_url() Function The parse_url() function is an inbuilt function in PHP which is used to return the components of a URL by parsing it. It parses an URL and return an associative array which contains its various components.
This is a bug on the data provider side, please let the data provider know as that should be fixed.
There is a way to extract the values 100% correctly if you know all possible key values and they are not too many. In that case, the regex could look like
new RegExp("[?&]+([^=&]+)=(.*?)(?=&(?:" + your_keys.map(function(x) {return x.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');}).join("|") + ")=|$)", "gi")
There is a fragile generic non-100% work-around for this, like
/[?&]+([^=&]+)=(.*?)(?=&[^=&]+=|$)/gi
See this regex demo. You may use it until the data provider fixes the issue and you do not know all possible keys.
Details
[?&]+
- 1 or more ?
or &
chars([^=&]+)
- Group 1: one or more chars other than =
and &
=
- an equal sign(.*?)
- Group 2: any 0+ chars other than line break chars, as few as possible(?=&[^=&]+=|$)
- followed with &
, one or more chars other than =
and &
and then =
, or the end of string.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With