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;
}
@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