Building URLs with parameters using jQuery

I have, for example, the following URL stored in a global variable:

var myUrl = "http://mydomain.com/something?row=1"; 

Then the function should add, say, another parameter called the "column". How does this function add parameters to a pre-existing URL string using jQuery?

An example of an expected generated string:

 "http://mydomain.com/something?row=1&column=9" 

The problem is that myUrl could also be simple:

 var myUrl = "http://mydomain.com/something"; 

(Note that options did not exist before)

+47
javascript jquery
Jan 17 '12 at 22:05
source share
6 answers

Check out the jQuery.param () function, which should do the trick.

http://api.jquery.com/jQuery.param/

Then you can simply create a function that adds the line generated with .param () to the URL.

+44
Jan 17 2018-12-12T00:
source share
 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); 

jsFiddle

+22
Jan 17 '12 at 22:25
source share

You do not need jQuery, use this function:

 var buildUrl = function(base, key, value) { var sep = (base.indexOf('?') > -1) ? '&' : '?'; return base + sep + key + '=' + value; } 

You would use it as follows:

 buildUrl('http://www.example.com/foo', 'test', '123'); buildUrl('http://www.example.com/foo?bar=baz', 'test', '123'); 
+18
Jan 17 2018-12-12T00:
source share

Keep everything in the object until you need a string.

First enter an object from several 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; }, {} ); 

Given the starting url: "http://mydomain.com/something?row=1&column=9"

 $_GET['column'] = 5; $.param( $_GET ); //"row=1&column=5" 

Array # reduce

+3
Jan 17 '12 at 22:17
source share

You can try this.

 myUrl += ((myUrl.indexOf('?') == -1) ? '?' : '&'); myUrl += "column=9"; 
+2
Jan 17 '12 at 22:11
source share
 if (myUrl.indexOf("?") != -1){ // contains query string } else { // doesn't } 
-2
Jan 17 '12 at 22:14
source share



All Articles