1

Given a string containing an absolute URL with a querystring parameter, what is the easiest way to replace the value of the parameter using JavaScript and/or MooTools?

e.g.

// Change this
'/foo/bar?frob=123456789'

// Into this
'/foo/bar?frob=abcdefg'

EDIT

The URL is not the location of the current window. It is a variable containing a string. I just want to manipulate this string.

Greg B
  • 14,597
  • 18
  • 87
  • 141

4 Answers4

3

Further to what you did, this may be better as it will extend String and it removes dependency on URI class...

(function() {

// deps on Types/String.toQueryString()
String.implement({

    fixQueryString: function(key, value) {
        var query = this.parseQueryString() || {};
        query[key] = value;
        return Object.toQueryString(query);
    }

});

// exports:
this.replaceUrlParameter = function(url, key, value) {
    var parts = url.split('?'), QS = parts[1] || null;

    return QS ? [parts[0], QS.fixQueryString(key, value)].join("?") : url;
};

})();

console.log(replaceUrlParameter('/foo/bar', 'frob', 'ownies'));
/foo/bar/
console.log(replaceUrlParameter('/foo/bar?frob=123123123', 'frob', 'ownies'));
/foo/bar?frob=ownies

http://jsfiddle.net/dimitar/fjj6W/

Dimitar Christoff
  • 26,147
  • 8
  • 50
  • 69
1

Sorry for bumping an old post but I think it's already in mootools. No need to write it yourself :-) http://mootools.net/docs/more/Types/URI#URI:setData

Or take a look here if your on a very old version of mootools: http://pilon.nl/mootools/2009/02/05/extra-browsersextras/

Lennart
  • 1,018
  • 1
  • 12
  • 27
0

If You want to do this without reloading the page, there is no way (this is part of the web browser security model). If You don't mind reloading the page, consider:

location.href='http://example.com/foo/bar?frob=baz'

An alternative without reloading is using location.hash, i.e.

location.hash = 'myhash'

to change url to http://example.com/foo/bar?frob=123456789#myhash

This is the basis of the Hash bang urls

maniek
  • 7,087
  • 2
  • 20
  • 43
0

This is the solution I came up with. This is dependent on MooTools.

function replaceUrlParameter (url, parameterName, newValue) {
    var uri = new URI(url);
    var uriBase = ri.get('directory') + uri.get('file');
    var query = uri.get('query').parseQueryString(false, true);
    query[parameterName] = newValue;

    uriBase += '?';
    for (var i in query) {
        if (i === 'undefined') continue;
        if (i === '') continue;
        uriBase += i + '=' + escape(query[i]) + '&';
    }
    return uriBase.substring(0, galleryLinkBase.length - 1);
}

This is specific to my usage but it might serve as a starting point for others in the future.

Greg B
  • 14,597
  • 18
  • 87
  • 141