Gags
Gags

Reputation: 3839

Change URL parameter onpage load

I want to change the 3rd parameter in my URL to a dynamic variable.

Eg. if my URL is http://example.com/A/B/Fixed_var_C then i want it to be changed to http://example.com/A/B/Dynamic_C

How can i achieve it by JQuery or javascript that too while the page loads?

I tried implementing few methods but not a success. Below is one of the methods:

window.history.pushState("object or string", "Title", "/new-url");

Upvotes: 2

Views: 939

Answers (2)

Sadikhasan
Sadikhasan

Reputation: 18601

url = "http://example.com/A/B/Fixed_var_C";
url = url.substr(0,url.lastIndexOf('/'))+"/Dynamic_C";
alert(url);

Demo

Upvotes: 2

ArinCool
ArinCool

Reputation: 1738

Try the following function:

function UpdateQueryString(key, value, url) {
    if (!url) url = window.location.href;
    var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"),
        hash;

    if (re.test(url)) {
        if (typeof value !== 'undefined' && value !== null)
            return url.replace(re, '$1' + key + "=" + value + '$2$3');
        else {
            hash = url.split('#');
            url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
            if (typeof hash[1] !== 'undefined' && hash[1] !== null) 
                url += '#' + hash[1];
            return url;
        }
    }
    else {
        if (typeof value !== 'undefined' && value !== null) {
            var separator = url.indexOf('?') !== -1 ? '&' : '?';
            hash = url.split('#');
            url = hash[0] + separator + key + '=' + value;
            if (typeof hash[1] !== 'undefined' && hash[1] !== null) 
                url += '#' + hash[1];
            return url;
        }
        else
            return url;
    }
}

Upvotes: 0

Related Questions