Skip to content

Instantly share code, notes, and snippets.

@stinoga
Created December 23, 2013 18:05
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • 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;
}
@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: jamezilla0@gmail.com
// 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