0

I am trying to read the "source" parameter and the "group" parameter from the url hash below. I have no idea how to use regex and keep ending up with blank variables.

How do I read "source" and "group" parameters from the url hash below

    console.log(urlObj.hash); // #source-items?source=1002&?group=Menu
    var source = urlObj.hash.replace( /.*source=/, "");
Jon Wells
  • 4,191
  • 9
  • 40
  • 69

2 Answers2

0

Try

function getParameterByName(urlString, name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(urlString);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

And invoke this by getParameterByName(urlObj.hash, "source");

Update : This is slightly modified version of the answer to Get query string values in JavaScript

Community
  • 1
  • 1
Ramesh
  • 13,043
  • 3
  • 52
  • 88
0

If you remove the ? after & and you can use something like this:

function parseParams() {
    var params = window.location.hash.split('?')[1].split('&').map(function(item) {
        return item.split('=');
    });
    var namedparams = {};

    for (i=-1; param = params[++i]; ) {
        namedparams[param[0]] = param[1];
    }

    return namedparams;
}

This is how you use this function:

var params = parseParams();
params.group; // the group parameter
params.source; // the source parameter
Wouter J
  • 41,455
  • 15
  • 107
  • 112