P粉1634659052023-08-21 11:15:52
Modern browsers provide the URLSearchParams
interface to handle search parameters. This interface has a delete
method to delete parameters based on their names.
if (typeof URLSearchParams !== 'undefined') { const params = new URLSearchParams('param1=1¶m2=2¶m3=3') console.log(params.toString()) params.delete('param2') console.log(params.toString()) } else { console.log(`您的浏览器 ${navigator.appVersion} 不支持URLSearchParams`) }
P粉5069638422023-08-21 09:30:25
"[&;]?" + parameter + "=[^&;]+"
Looks dangerous because the parameter 'bar' will match:
?a=b&foobar=c
In addition, if parameter
contains any characters that have special meaning in regular expressions, such as '.', this regular expression will fail. And it's not a global regex, so only one instance of the parameter will be removed.
I wouldn't use a simple regex to do this, I would parse the parameters and discard the ones I don't need.
function removeURLParameter(url, parameter) { //如果你有一个location/link对象,最好使用l.search var urlparts = url.split('?'); if (urlparts.length >= 2) { var prefix = encodeURIComponent(parameter) + '='; var pars = urlparts[1].split(/[&;]/g); //反向迭代可能会破坏性 for (var i = pars.length; i-- > 0;) { //字符串.startsWith的习惯用法 if (pars[i].lastIndexOf(prefix, 0) !== -1) { pars.splice(i, 1); } } return urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : ''); } return url; }