0

This handy function adds and modifies a key/value in the URL and was posted by a user Joshua Stewardson:

function updateQueryString(key, value) {
    if (!uri) var uri = window.location.hash;
    var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
    var separator = uri.indexOf('?') !== -1 ? "&" : "?";
    if (uri.match(re)) {
        return uri.replace(re, '$1' + key + "=" + value + '$2');
    }
    else {
        return uri + separator + key + "=" + value;
    }
};

(I modified it slightly from the original).

It does just what I need except for two things:

One: I am using this for a location hash. I have a function that adds three key-values to the URL on one click and I can't figure out how to prevent it from adding a "?" after the hash, e.g.:

http://localhost/product-list?minify=false#?catId=2&prodId=3&subId=4

Modifying the line

var separator = uri.indexOf('#') !== -1 ? "&" : "#"; // modified

solves the "?" issue, but ignores the first key value and adds it again at the end, e.g.

http://localhost/product-list?minify=false#?catId=1&prodId=2&subId=3&catId=2

Two: I'd like to modify the function so that it removes the key if the value is empty ('') or null, e.g.:

updateQueryString('catId','') || updateQueryString('catId',null)

My RegEx skills are not sharp enough for this. Any help appreciated.

Thanks.

PARTIAL ANSWER

I answered part 1 of my question. Revised code below:

updateQueryString = function (key, value) {
    if (!uri) var uri = window.location.hash;
    var re = new RegExp("([#|&])" + key + "=.*?(&|$)", "i"); // added "or" and added hash
    var separator = uri.indexOf('#') !== -1 ? "&" : "#"; // looks for hash in uri, not ampersand
    if (uri.match(re)) {
        return uri.replace(re, '$1' + key + "=" + value + '$2');
    }
    else {
        return uri + separator + key + "=" + value;
    }
};

If anyone has a suggestion about how to remove the hash parameter if passed an empty or null value, I'm all ears.

Community
  • 1
  • 1
dylanmac
  • 343
  • 1
  • 6
  • 19

1 Answers1

2

Instead of badly trying to reinvent the wheel I would strongly advise you to keep it simple and use a library. Have a look at URI.js and jsUrl.

Lodewijk Bogaards
  • 18,519
  • 2
  • 25
  • 49
  • I take your point. Unfortunately URI.js (with the hash manipulation add-on) is pretty large. And jsurl is small but forces me to check for null values and then call the delete method. Not the end of the world but in that respect no better than what I have now. – dylanmac Mar 03 '14 at 21:23
  • The more I explore the alternatives, the better I like this function as imperfect as it is. – dylanmac Mar 04 '14 at 01:05