I need to get URL search parameters in an object, for example; Generating http://example.com/?a=x&b=y&d#pqr to {a: x, b: y, d: 1}
Below is the method I used to get it, how can I improve it? Any suggestion ...
var urlParamKeyVals = new array (); Var pieces = new array (); Var UrlParams = {}; If (window.location.search.length) {var urlSearchString = window.location.search; If (urlSearchString.charAt (0) == '?') {UrlSearchString = urlSearchString.substr (1); UrlParamKeyVals = urlSearchString.split ("& amp;"); }} For (var i = 0; i & lt; urlParamKeyVals.length; i ++) {pieces = urlParamKeyVals [i] .split ("="); If (pieces length == 1) {UrlParams [pieces [0]] = 1; } And {UrlParams [pieces [0]] = pieces [1]; }} UrlParams; I have created a small function for the same purpose some time ago:
< P>
{str = str || Window.location.search; Var result = {}; Str.replace (/ [[^? = & Amp;] +) (?: [& Amp; #] | = ([^ & amp; #] *)) / g, function (match, key, value) { Result [key] = value || 1;}); Return result; } GetQueryStringValues ("http://example.com/?a=x&b=c&d#pqr"); // returns {a = "x", b = "c", d = 1}
Comments
Post a Comment