Nasir Zia Nasir Zia - 5 months ago 7
Javascript Question

Adding GET Parameter at end of all URLs in a Page using jQuery

I have found a similar questions which was very well explained, the only difference is that I want this to be done through jQuery and not PHP.

Example:

If i want to add category=action

$url="http://www.acme.com";
// will add ?category=action at the end

$url="http://www.acme.com/movies?sort=popular";
// will add &category=action at the end


If you notice i'm trying to not repeat the question mark if it's found.

The url is just a string.

What a reliable function to append a specific GET parameter?

Answer

Use this code

var url = "http://www.acme.com";

if (url.match(/\?/g)){
    if (url.match(/=/g))
        url += "&";
} else
    url += "?";

url += "category=action";

You can test different URL in it. Result will be same.

addParam("http://www.acme.com/movies", "category=action");
addParam("http://www.acme.com/movies?sort=popular", "category=action");

function addParam(url, param){
    if (url.match(/\?/g)){
        if (url.match(/=/g))
            url += "&";
    } else
        url += "?";    
    url += param;
    console.log(url);
}