Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove some parameters from an URL string?

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"

like image 988
CommonSenseCode Avatar asked Mar 09 '17 16:03

CommonSenseCode


2 Answers

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.

like image 88
georgeawg Avatar answered Oct 06 '22 01:10

georgeawg


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

like image 36
Mistalis Avatar answered Oct 06 '22 01:10

Mistalis