Search code examples
javascripturlhref

Function edit needed


Currently, the following code takes a href and lines up all the parameters to be called upon later:

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(
        /[?&]+([^=&]+)=([^&]*)/gi,
        function (m, key, value) {
            vars[key] = value;
        });
    return vars;
}

That works with a href that has parameters set up like parameter=value in the url. I found this function online and do not understand a lot of javascript but need to edit it so that instead of = being the dividing factor between parameter and value it is %3A instead. So for example parameter%3Avalue due to a different format on the website I am working on. I am not sure how the function works so I am having a hard time editing it. Thank you for your help.


Solution

  • If there are multiple items you need in decoded format, you should try applying decodeURIComponent to the href string first. If it's just the %3A that you want decoded throughout, it would probably be easiest to just decode that first (so that the string does look like it uses = signs).

    function getUrlVars() {
            var vars = {};
    
            var partsWithEqSign = window.location.href.replace(/%3A/g, "=");
    
            var parts = partsWithEqSign.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
                vars[key] = value;
            });
            return vars;
        }
    

    Btw, the bit of code being used involves regular expressions, which are one of the most difficult concepts in JavaScript, but are really useful once you learn them.