Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse URL parameters with "&" characters without an "=" after

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

like image 442
Wanda Avatar asked May 13 '19 08:05

Wanda


People also ask

How do you parse a URL?

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.

How do you separate query parameters in URL?

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 (&).

How parse URL in PHP?

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.


1 Answers

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.
like image 124
Wiktor Stribiżew Avatar answered Oct 07 '22 02:10

Wiktor Stribiżew