简体   繁体   中英

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]);
    })();

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

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM