Skip to content

Instantly share code, notes, and snippets.

@blackmiaool
Last active October 26, 2018 09:58
Show Gist options
  • Save blackmiaool/ca85fdde49f6463567871de6a40fdb50 to your computer and use it in GitHub Desktop.
Save blackmiaool/ca85fdde49f6463567871de6a40fdb50 to your computer and use it in GitHub Desktop.
addParam
export function addParam(url, key, value) {
url = url.replace(new RegExp(`[?&]${key}=[^&]*&?`, 'g'), str => (str[str.length - 1] === "&" ? str[0] : ""));
const hashReg = /#[\w-]+$/;
let hash = url.match(hashReg) || [];
hash = hash[0] || "";
url = url.replace(hashReg, "");
let linkSymbol = "&";
if (url.indexOf("?") === -1) {
linkSymbol = "?";
}
return `${url}${linkSymbol}${key}=${value}${hash}`;
}
@blackmiaool
Copy link
Author

blackmiaool commented Jul 9, 2018

[
    addParam("//a.com/a/img","w","1")==="//a.com/a/img?w=1",
    addParam("//a.com/a/img?c=1","w","1")==="//a.com/a/img?c=1&w=1",
    addParam("//a.com/a/img?c=1&w=2","w","1")==="//a.com/a/img?c=1&w=1",
    addParam("//a.com/a/img?w=2&c=1","w","1")==="//a.com/a/img?w=1&c=1",
    addParam("//a.com/a/img?w=2&c=1#a","w","1")==="//a.com/a/img?w=1&c=1#a",
]

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