Arens Myzyri Arens Myzyri - 2 months ago 12
HTML Question

How to divide an URL string into parts and insert into variables with jquery

I have an URL:

http://example.org/collections/inventory/cf-size-m+cf-type-capri+cf-vendor-manduka


I'm using this script for taking the URL parameters and inserting them into variables:

<script>
var getUrlParameter2 = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
var name = getUrlParameter2('myvar');
$("#Inventory").html(name);
document.write('<p>URL: '+name+'</p>');
</script>


It works when I have something like this:

`http://example.org/collections/inventory/?myvar=resultsblabla`


So going back to the URL above:

http://example.org/collections/inventory/cf-size-m+cf-type-capri+cf-vendor-manduka


I want to have where
cf-size
the variable and
m
the value and so go on for all the others.

Please let me know if something is not clear so I can modify the question again. Thanks for your help.

Answer

You can do it with following javascript code:

var url = "http://example.org/collections/inventory/cf-size-m+cf-type-capri+cf-vendor-manduka";

var lstIdxOfSlash = url.lastIndexOf("/");
var paramPart = url.substring(lstIdxOfSlash + 1);
var paramValArray = paramPart.split("+");

var keyValPair = {};

for (var i = 0; i < paramValArray.length; i++) {

  var lstIdxOfDash = paramValArray[i].lastIndexOf("-");
  
  var key = paramValArray[i].substring(0,lstIdxOfDash);
  var val = paramValArray[i].substring(lstIdxOfDash+1);
                                       
  keyValPair[key] = val;                                 
}

console.log(keyValPair);