Pinch
Pinch

Reputation: 4207

Extract values from href attribute string using JQuery

I would like to extract values from href attribute string using JQuery

$(this).attr("href")

will give me

?sortdir=ASC&sort=Vendor_Name

What i need is these values parsed into an array

myArray['sort']

myArray['sortdir']

Any ideas? Thanks!

BTW , I saw somewhere else on SO the following similar idea to be used with a query string. I could not tweak it for my needs just yet.

var urlParams = {};
    (function () {
        var match,
    pl = /\+/g,  // Regex for replacing addition symbol with a space
    search = /([^&=]+)=?([^&]*)/g,
    decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
    query = window.location.search.substring(1);

        while (match = search.exec(query))
            urlParams[decode(match[1])] = decode(match[2]);
    })();

Upvotes: 3

Views: 1703

Answers (4)

kiranvj
kiranvj

Reputation: 34107

Try this

function getURLParameter(name, string) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(string)||[,null])[1]
    );
}

var string = $(this).attr("href");

alert(getURLParameter("sort",string));

Demo here http://jsfiddle.net/jbHa6/ You can change the var string value and play around.

EDIT

Removed the second example, since that code is not that good and does not serve the purpose.

Upvotes: 0

Ram
Ram

Reputation: 144659

Try the following:

var href = $(this).attr("href")
href = href.replace('?', "").split('&');

var myArr = {};
$.each(href, function(i, v){
   var s = v.split('=');
   myArr[s[0]] = s[1];    
});

DEMO

Upvotes: 1

Akoben
Akoben

Reputation: 255

You could use jQuery BBQ's deparam function from here:

http://benalman.com/code/projects/jquery-bbq/examples/deparam/

Upvotes: 0

Xavier Lambros
Xavier Lambros

Reputation: 876

Perhaps is there a better solution but to be quick I should have do something like that

var url = $(this).attr("href");
url = url.replace("?sortdir=", "");
url = url.replace("sort=", "");
myArray['sort'] = url.split("&")[1]; // Or use a temporary tab for your split
myArray['sortdir'] = url.split("&")[0];

That solution depends if your url is still like ?sortdir=ASC&sort=Vendor_Name

Upvotes: 0

Related Questions