Add or update URL query parameter in JavaScript

Add or update URL query parameter with respect to number of parameters and its position.
Usage:

  • ‘http://www.website.com/’.urlQueryParameter(‘id’, 2) => http://www.website.com/?id=2
  • ‘http://www.website.com/?type=1’.urlQueryParameter(‘id’, 2) => http://www.website.com/?type=1&id=2
String.prototype.isString = true;
String.prototype.urlQueryParameter = function (key, value) {
    var uri = this;
    if (uri.isString) {
        var  = new RegExp("([?|&])" + key + "=.*?(&|$)", "i");
        var separator = uri.indexOf('?') !== -1 ? "&" : "?";
        if (uri.match(regEx))
            uri = uri.replace(regEx, '$1' + key + "=" + value + '$2');
        else
            uri = uri + separator + key + "=" + value;
    }
    return uri;
};

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Post

%d bloggers like this: