Add Query Parameter

by Patrick Hund

JavaScript

var urls = [
    "https://developer.mozilla.org",
    "https://developer.mozilla.org/en-US/docs/Learn/",
    "https://developer.mozilla.org/en-US/search?q=URL",
    "http://www.example.com:80/path/to/myfile.html?key1=value1&key2=value2#SomewhereInTheDocument",
    "/forum/aktion/EditPost.html?postId=33429617&threadId=4655032&boardId=55",
    "#post33429617"
];

urls.forEach(function (url) {
	console.log("--------");
    console.log("input:    ", url);
	var newUrl = addQueryParameter(url, "foo", "bar");
    console.log("output:   ", newUrl);
});

function addQueryParameter(url, name, value) {
   var parts = url.match(/^([^?#]+)?(\?[^#]+)?(#.+)?$/),
       base = parts[1],
       query = parts[2],
       hash = parts[3],
       hasBase = base !== undefined,
       hasQuery = query !== undefined,
       hasHash = hash !== undefined;
   return (hasBase ? base : "") + (hasQuery ? query + "&" : "?") + name + "=" + value + (hasHash ? hash : "");
}