How to remove some parameters from an URL string?

2019-07-14 18:05发布

I have this var storing a string that represents a URL full of parameters. I'm using AngularJS, and I'm not sure if there is any useful module (or maybe with plain JavaScript) to remove the unneeded URL parameters without having to use regex?

For example I need to remove &month=05 and also &year=2017 from:

var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017"

5条回答
唯我独甜
2楼-- · 2019-07-14 18:17

Sure you can use RegExr: ((&)year=([^&]))|((&)month=([^&]))

use:

url = url.replace(/(year=([^&]*))|(month=([^&]*))/g, '');

Read more regex :)...

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>

查看更多
再贱就再见
3楼-- · 2019-07-14 18:21

Use the URLSearchParams API:

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);

The advantage of using this API is that it works with and creates strings with correct percent encoding.

For more information, see MDN Developer Reference - URLSearchParams API.

查看更多
一纸荒年 Trace。
4楼-- · 2019-07-14 18:30

You can use the library https://www.npmjs.com/package/query-string

Convert the params to an object and then just use delete params.year delete params.month and convert it back and add it to the original url

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'
查看更多
虎瘦雄心在
5楼-- · 2019-07-14 18:37

Using string replace:

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);

查看更多
forever°为你锁心
6楼-- · 2019-07-14 18:38

You can use this function that take 2 parameters: the param you are trying to remove and your 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);


Alternative solution with a regex

查看更多
登录 后发表回答