3

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

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

@Pinch have you checked the fiddle? it's an object and it's not empty.
Your approach works as well, i am still unable to give you a +1, until my rep goes up.. anyone else please give him a +1!
0

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.

1 Comment

thanks so much the first approach worked like a dandy. If that is a compliment.
0

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

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.