0

I need your help,

Given the following query string with backslashes in it:

"G:\\AS\\Asf\\ASF\\IMTS\\V11\\IMTS.hta?report=true&type=note"

How can I parse out the values of report and type?

example:

GetUrlParam('report') returns true

GetUrlParam('type') returns note
BobbyJones
  • 1,331
  • 1
  • 26
  • 44

3 Answers3

0

var str = "G:\\AS\\Asf\\ASF\\IMTS\\V11\\IMTS.hta?report=true&type=note";

function getUrlParam(param){
  var rg = new RegExp(param + "=(\\w+)"),
      res = str.match(rg)[1];
      console.log(res);
}

getUrlParam('report');
getUrlParam('type');
kind user
  • 40,029
  • 7
  • 67
  • 77
0

How about this regex (?<=[\?&])([^=]+)=([^&]+)? The first matching group is the parameter and the second matching group is the value.

Given your example, the matching groups are:

  • Match 1 report=true Group 1. report Group 2. true

  • Match 2 type=note Group 1. type Group 2. note

Chuancong Gao
  • 654
  • 5
  • 7
0

I've modified an answer I've found on stackoverflow and have come up with this:

var url = "G:\\AS\\Asf\\ASF\\IMTS\\V11\\IMTS.hta?report=true&type=note"

var vars = {}, hash;
var hashes = url.slice(url.indexOf('?') + 1).split('&');  // starts query string after index of ? and splits query string based on &

for (var i = 0; i < hashes.length; i++) {
  hash = hashes[i].split('=');      // creates new array on each iteration (property and key)
  vars[hash[0]] = hash[1];      // add key value pair to object
}

console.log(vars);

function GetUrlParams(key) {
  if (typeof vars[key] !== 'undefined') {
    return vars[key];
  }
}

console.log(GetUrlParams('report'));
console.log(GetUrlParams('type'));
Community
  • 1
  • 1
Anthony
  • 1,439
  • 1
  • 19
  • 36