Skip to content

Instantly share code, notes, and snippets.

@stinoga
Created December 23, 2013 18:05
Show Gist options
  • Save stinoga/8101816 to your computer and use it in GitHub Desktop.
Save stinoga/8101816 to your computer and use it in GitHub Desktop.
Replacing query string parameter values.
// Update the appropriate href query string parameter
function paramReplace(name, string, value) {
// Find the param with regex
// Grab the first character in the returned string (should be ? or &)
// Replace our href string with our new value, passing on the name and delimeter
var re = new RegExp("[\\?&]" + name + "=([^&#]*)"),
delimeter = re.exec(string)[0].charAt(0),
newString = string.replace(re, delimeter + name + "=" + value);
return newString;
}
@shanecp
Copy link

shanecp commented Nov 28, 2014

Thanks for the code. You might want to check if the replacing param is present at the first place.

function paramReplace(name, string, value) {
        // Find the param with regex
        // Grab the first character in the returned string (should be ? or &)
        // Replace our href string with our new value, passing on the name and delimeter

        var re = new RegExp("[\\?&]" + name + "=([^&#]*)");
        var matches = re.exec(string);
        var newString;

        if (matches === null) {
            // if there are no params, append the parameter
            newString = string + '?' + name + '=' + value;
        } else {
            var delimeter = matches[0].charAt(0);
            newString = string.replace(re, delimeter + name + "=" + value);
        }
        return newString;
    }

@slaveofcode
Copy link

I think this is better

function queryStringUrlReplacement(url, param, value) 
{
    var re = new RegExp("[\\?&]" + param + "=([^&#]*)"), match = re.exec(url), delimiter, newString;

    if (match === null) {
        // append new param
        var hasQuestionMark = /\?/.test(url); 
        delimiter = hasQuestionMark ? "&" : "?";
        newString = url + delimiter + param + "=" + value;
    } else {
        delimiter = match[0].charAt(0);
        newString = url.replace(re, delimiter + param + "=" + value);
    }

    return newString;
}

This function will add new parameter if not exist before, and will replace the old one if exist, without messing with any of existing querystring parameters.

to use var newUrl = queryStringUrlReplacement('http://www.tomatmerah.com/', 'page', '18');

@iratherscribble
Copy link

@slaveofcode Nice work. You might want to update to do a case-insensitive match, otherwise it will duplicate the parameters to the resulting string. Minor update, but overall a great solution.

var re = new RegExp("[\\?&]" + param + "=([^&#]*)", "i"), match = re.exec(url), delimiter, newString;

@jbernard1
Copy link

jbernard1 commented Jul 22, 2016

Using this thread I have compiled a String prototype to easily replace params in a URL enjoy.

// Replace or add parameters to a url
// Author: James Bernard
// email: [email protected]
// Version: 0.5
String.prototype.replaceParam = function(paramsObject, add) 
{
    var originalUrl = this.toString();
    var params = Object.keys(paramsObject);
    var newUrl = originalUrl;
    params.forEach(function(param){
        // Author: iratherscribble@gitHub
        var re = new RegExp("[\\?&]" + param + "=([^&#]*)", "i"), match = re.exec(newUrl), delimiter, newString;
        // =============
        // Author: slaveofcode@gitHub
        if (match === null && add) {
            // append new param
            var hasQuestionMark = /\?/.test(url); 
            delimiter = hasQuestionMark ? "&" : "?";
            newUrl = newUrl + delimiter + param + "=" + paramsObject[param];
        } else if(match){
            delimiter = match[0].charAt(0);
            newUrl = newUrl.replace(re, delimiter + param + "=" + paramsObject[param]);
        } else {
            console.error("Parameter", "'" + param + "'", "Does not exist in url: ", originalUrl); 
            console.error("To add these parameters to this url please change your method call to: replaceParam([Object], [Boolean=true])")
        }
    })

    return newUrl;
}

@jbernard1
Copy link

jbernard1 commented Jul 22, 2016

Patched this to work with urls that contain ?: or &: in their parameters.

// Replace or add parameters to a url
// Author: James Bernard
// email: [email protected]
// Version: 0.6
String.prototype.replaceParam = function(paramsObject, add) 
{
    var originalUrl = this.toString();
    var params = Object.keys(paramsObject);
    var newUrl = originalUrl;
    params.forEach(function(param){
        // Author: iratherscribble@gitHub
        var re = new RegExp("[\\?&:]" + param + "=([^&#]*)", "i"), match = re.exec(newUrl), delimiter, newString;
        // =============
        // Author: slaveofcode@gitHub
        if (match === null && add) {
            // append new param
            var hasQuestionMark = /\?/.test(url); 
            var hasColon = /\:/.test(url);
            delimiter = hasColon ? (hasQuestionMark ? "&:" : "?:") : (hasQuestionMark ? "&" : "?");
            newUrl = newUrl + delimiter + param + "=" + paramsObject[param];
        } else if(match){
            delimiter = match[0].charAt(0);
            newUrl = newUrl.replace(re, delimiter + param + "=" + paramsObject[param]);
        } else {
            console.error("Parameter", "'" + param + "'", "Does not exist in url: ", originalUrl); 
            console.error("To add these parameters to this url please change your method call to: replaceParam([Object], [Boolean=true])")
        }
    })

    return newUrl;
}

@whoisgregg
Copy link

@jbernard1: Thanks for the code! Noticed that these two lines:

            var hasQuestionMark = /\?/.test(url); 
            var hasColon = /\:/.test(url);

Should be:

            var hasQuestionMark = /\?/.test(newUrl); 
            var hasColon = /\:/.test(newUrl);

Cheers! :)

@adamvleggett
Copy link

adamvleggett commented Aug 5, 2016

This is my preference, and it covers the cases I can think of. Can anyone think of a way to reduce it to a single replace?

function setParam(uri, key, val) {
    return uri
        .replace(new RegExp("([?&]"+key+"(?=[=&#]|$)[^#&]*|(?=#|$))"), "&"+key+"="+encodeURIComponent(val))
        .replace(/^([^?&]+)&/, "$1?");
}

@chenchangwen
Copy link

/**

  • 替换url参数
  • @param {String} name 参数名
  • @param {String} value 参数值
  • @param {String} url 如果该值存在,则以该值为基准替换
    /
    function replaceUrlParam(name, value, newUrl) {
    let urlMark = '';
    let url = newUrl || location.href;
    let nameIndex = url.indexOf(name);
    //删除参数
    if (value === '') {
    //取当前参数前一位字符
    urlMark = url.charAt(nameIndex - 1);
    if (!/?|&/.test(urlMark)) {
    urlMark = '';
    }
    let reg = new RegExp("\" + urlMark + name + '=' + "[^&]
    ");
    url = url.replace(reg, '');
    }
    //如果一个参数都没有
    else if (window.location.search === "" && new URL(location.href).searchParams.get(url) === '') {
    urlMark = '?';
    url = url + urlMark + name + '=' + value;
    }
    //有参数, 有当前参数
    else if (nameIndex > -1) {
    //这个urlMark 可能会是 ? 或 &
    urlMark = url.charAt(nameIndex - 1);
    let reg = new RegExp("\" + urlMark + name + '=' + "[^&]*");
    url = url.replace(reg, urlMark + name + '=' + value);
    }
    //有参数,但没有当前参数
    else if (nameIndex === -1) {
    urlMark = '&';
    url = url + urlMark + name + '=' + value;
    }
    //替换为正确的符号参数
    if (url.indexOf('?') === -1) {
    let matchParam = url.match('&');
    if (matchParam !== null) {
    url = url.replace(/&/, '?');
    }
    }
    return url;
    }

this is better

@Mike-Savin
Copy link

To replace all the query parameters with given value you can use something like this:

url.replace(/([?&])(((?![?&#=]).)*=)((?![?&#=]).)*/g, '$1$2xxx');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment