Skip to content

Instantly share code, notes, and snippets.

@guoshuai93
Last active August 16, 2018 06:30
Show Gist options
  • Save guoshuai93/e2083ee8a9cc53eae42373e5e1bec05d to your computer and use it in GitHub Desktop.
Save guoshuai93/e2083ee8a9cc53eae42373e5e1bec05d to your computer and use it in GitHub Desktop.
获取url指定key对应的值
// url = 'https://www.baidu.com/s?wd=%E6%96%B0%E5%9E%A3%E7%BB%93%E8%A1%A3'
var urlParams = function (key) {
var ret = location.search.match(new RegExp('(\\?|&)' + key + '=(.*?)(&|$)'))
return ret && decodeURIComponent(ret[2])
}
urlParams('wd'); // '新垣结衣'
/**
* removeParam 删除 URL 中指定参数
* @param {name} 参数名
* @param {url} 指定 URL,可选。默认当前地址 location.href
*/
export const removeParam = (name, url) => {
if (typeof name !== 'string') return false;
if (!url) url = window.location.href;
var urlparts = url.split('?');
var prefix = encodeURIComponent(name + '=');
var pars = urlparts[1].split(/[&;]/g);
var i = 0,
len = pars.length;
for (; i < len; i++) {
if (encodeURIComponent(pars[i]).lastIndexOf(prefix, 0) !== -1) {
pars.splice(i, 1);
}
}
url = urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : '');
return url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment