javascripturl-parametersuriencoding

Get two URL parameters - but need to preserve & symbol


I need to get two parameters from a URL, and they could potensially contain an & symbol or a space. as part of the search string.

Example: mysite.com?param1=Bower & Wilkins?param2=Speakers

I realize that Bower & Wilkins contains the obvious symbol for getting the second parameter, but can I replace it with something else?

When trying this function, can easily return a single parameter:

URL: mysite.com?param1=Bower%20&%20Wilkins

function getQueryStringValue(key) {
  return decodeURIComponent(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURIComponent(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^]*))?)?.*$", "i"), "$1"));
}
var param1 = getQueryStringValue("param1"); // Bower & Wilkins

How can I get the second parameter and how must I construct the URL. Can I use another symbol than & for listing the second parameter?

What I need:

var param1 = getQueryStringValue("param1"); // Bower & Wilkins

var param2 = getQueryStringValue("param2"); // Speakers


Solution

  • The & within the param needs to be encoded as %26. This means you need to substitute before running the parameters through encodeURI or use encodeURIComponent on the value.

    The input should be "mysite.com?param1=Bower%20%26%20Wilkins&param2=Speakers".

    To get the result you could try something like this

    function getQueryStringValue(url, key) {
        var params = {};
        var url_params = url.split("?", 2);
        if (url_params.length > 1) {
            var param_list = url_params[1].split("&");
            param_list.map(function (param_str) {
                var kv = param_str.split("=", 2);
                params[kv[0]] = kv[1];
            });
        }
        return (key in params)? decodeURIComponent(params[key]) : ''
    }
    
    var url = "mysite.com?param1=Bower%20%26%20Wilkins&param2=Speakers";
    console.log("Bower & Wilkins" === getQueryStringValue(url, "param1"));
    console.log("Speakers" === getQueryStringValue(url, "param2"));
    console.log("" === getQueryStringValue(url, "param3"));