Reputation: 11475
I have for example the following URL stored in a global variable:
var myUrl = "http://mydomain.com/something?row=1";
Then a function has to add let's say another parameter called "column". How would that function add parameters to a pre-existing URL string using jQuery?
Example of the expected generated string:
"http://mydomain.com/something?row=1&column=9"
The problem is that myUrl
could also be just:
var myUrl = "http://mydomain.com/something";
(Notice that there are not pre-existing parameters)
Upvotes: 58
Views: 106238
Reputation: 207501
var myUrl = "http://mydomain.com/something";
function addQSParm(name, value) {
var re = new RegExp("([?&]" + name + "=)[^&]+", "");
function add(sep) {
myUrl += sep + name + "=" + encodeURIComponent(value);
}
function change() {
myUrl = myUrl.replace(re, "$1" + encodeURIComponent(value));
}
if (myUrl.indexOf("?") === -1) {
add("?");
} else {
if (re.test(myUrl)) {
change();
} else {
add("&");
}
}
}
console.log(myUrl);
addQSParm("foo", "asdf");
console.log(myUrl);
addQSParm("bar", "qwerty");
console.log(myUrl);
addQSParm("foo", "123");
console.log(myUrl);
Upvotes: 25
Reputation: 140220
Keep everything in an object until you actually need a string.
First populate the object from some initial values:
var $_GET = location.search.substr(1).split("&").reduce( function( obj, val ){
if( !val ) return obj;
var pair = val.split("=");
obj[pair[0]] = pair[1];
return obj;
}, {} );
Considering initial url of: "http://mydomain.com/something?row=1&column=9"
$_GET['column'] = 5;
$.param( $_GET ); //"row=1&column=5"
Upvotes: 4
Reputation: 224
if (myUrl.indexOf("?") != -1){
// contains query string
}
else
{
// doesn't
}
Upvotes: -2
Reputation: 69905
You can try this.
myUrl += ((myUrl.indexOf('?') == -1) ? '?' : '&');
myUrl += "column=9";
Upvotes: 3
Reputation: 351506
You don't need jQuery, use a function like this:
var buildUrl = function(base, key, value) {
var sep = (base.indexOf('?') > -1) ? '&' : '?';
return base + sep + key + '=' + value;
}
You would use it like this:
buildUrl('http://www.example.com/foo', 'test', '123');
buildUrl('http://www.example.com/foo?bar=baz', 'test', '123');
Upvotes: 21
Reputation: 1600
Check out the jQuery function .param(), that should do the trick.
http://api.jquery.com/jQuery.param/
You can then just create a function which appends the string generated by .param() to a url.
Upvotes: 58