Michael
Michael

Reputation: 33

need a script to split and assign values Jquery

I am trying to separate and reassign values in a variable. What I have is

#&first=1&second=2

can anyone help with a script that will separate and assign this values to another variable so it would be like

var first= val.(first);
var second= val.(second);

I am new to jquery so I am not even sure if I am using the correct syntax.

Thanks

Upvotes: 3

Views: 74

Answers (3)

Brad Christie
Brad Christie

Reputation: 101604

Here's the one that breaks down the GET variables in to key/value pairs, which I believe is what you're after: http://snipplr.com/view/12208/javascript-url-parser/

Also, you can take a look at parseURI, a javascript function that can dissect a URL with GET parameters and grab sections.

Sorry for being quick to post, I thought I found the right function the first time.

Upvotes: 3

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

You could do something like this:

var val = "#&first=1&second=2";

var first = gup(val, "first");
var second = gup(val, "second");


function gup(str, name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(str);
    if (results == null) return "";
    else return results[1];
}

Checkout the example on jsfiddle: http://jsfiddle.net/WxnJq/

Upvotes: 3

Stephane Gosselin
Stephane Gosselin

Reputation: 9148

JQuery has no builtin way of dealing with querystrings, so I use a plugin for this. You can get it here, works great.

Upvotes: 1

Related Questions