58

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)

2
  • What do you need it for? Commented Jan 17, 2012 at 22:07
  • There is a component that needs that URL and has it's own way to fetch data using AJAX. Commented Jan 17, 2012 at 22:10

6 Answers 6

58

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.

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

2 Comments

What happens if the string already has parameters? Or the string already has parameters with the same name?
In that case the best thing is probably to parse the URL up front, then rebuild it later with jQuery.param or similar. "The string is a stark data structure..."
25
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

1 Comment

Using the regex ([?&]" + name + "=)([^&]+)? will work better. This enables finding empty parameters within a URL.
21

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');

2 Comments

This does not take into account that the parameter could already exist. It would be obvious when you invoke it the way you do in the examples, but it would not be obvious when you add parameters to the URL when all the parameters come from other variables.
This is missing URL encoding.
4

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"

Array#reduce

Comments

3

You can try this.

myUrl += ((myUrl.indexOf('?') == -1) ? '?' : '&');
myUrl += "column=9";

Comments

-2
if (myUrl.indexOf("?") != -1){
    // contains query string
}
else
{
    // doesn't
}

2 Comments

This question asks about constructing the query string, not reading it.
I don't think you read the question. It's about detecting query string parameters.

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.