我有这个var
存储一个字符串,表示一个充满参数的URL。我正在使用AngularJS,我不确定是否有任何有用的模块(或者可能使用普通的JavaScript)来删除不需要的URL参数而不必使用正则表达式?
例如,我需要从
中移除&month=05
和&year=2017
var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017"
答案 0 :(得分:5)
您可以使用带有2个参数的function:您要删除的param
和source URL
:
function removeParam(key, sourceURL) {
var rtn = sourceURL.split("?")[0],
param,
params_arr = [],
queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
if (queryString !== "") {
params_arr = queryString.split("&");
for (var i = params_arr.length - 1; i >= 0; i -= 1) {
param = params_arr[i].split("=")[0];
if (param === key) {
params_arr.splice(i, 1);
}
}
rtn = rtn + "?" + params_arr.join("&");
}
return rtn;
}
var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017";
var url2 = removeParam("month", url);
var url3 = removeParam("year", url2);
console.log(url3);

答案 1 :(得分:4)
var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017"
var urlParts = url.split('?');
var params = new URLSearchParams(urlParts[1]);
params.delete('month');
params.delete('year')
var newUrl = urlParts[0] + '?' + params.toString()
console.log(newUrl);
使用此API的优势在于它可以使用并创建具有正确percent encoding.
的字符串答案 2 :(得分:1)
使用字符串替换:
var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017";
var modifiedUrl = url.replace('&month=05','').replace('&year=2017','');
console.log(modifiedUrl);

答案 3 :(得分:1)
当然你可以使用RegExr:((&) year =([^&] ))|((&) month =([^& ] ))强>
使用:
url = url.replace(/(year=([^&]*))|(month=([^&]*))/g, '');
阅读更多正则表达式:)...
function removeParam(name, url){
return url.replace('/((&)*' + name + '=([^&]*))/g','');
}
var url = "?derivate=21&gear_type__in=13&engine=73&month=05&year=2017"
function removeParam(name, _url){
var reg = new RegExp("((&)*" + name + "=([^&]*))","g");
return _url.replace(reg,'');
}
url = removeParam('year', url);
url = removeParam('month', url);
document.getElementById('url-replace').innerHTML = url;

<div id="url-replace"></div>
&#13;
答案 4 :(得分:0)
增强@Mistalis的答案。
A
是唯一的参数First
答案 5 :(得分:-1)
您可以使用库https://www.npmjs.com/package/query-string
将参数转换为对象,然后仅使用delete params.year delete params.month
并将其转换回并添加到原始网址
const queryString = require('query-string');
console.log(location.search);
//=> '?foo=bar'
const parsed = queryString.parse(location.search);
console.log(parsed);
//=> {foo: 'bar'}
console.log(location.hash);
//=> '#token=bada55cafe'
const parsedHash = queryString.parse(location.hash);
console.log(parsedHash);
//=> {token: 'bada55cafe'}
parsed.foo = 'unicorn';
parsed.ilike = 'pizza';
const stringified = queryString.stringify(parsed);
//=> 'foo=unicorn&ilike=pizza'
location.search = stringified;
// note that `location.search` automatically prepends a question mark
console.log(location.search);
//=> '?foo=unicorn&ilike=pizza'