How to remove some parameters from an URL string?

18,431

Solution 1

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

Solution 2

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.

Solution 3

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>

Solution 4

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

Share:
18,431
CommonSenseCode
Author by

CommonSenseCode

Software Skills: JavaScript NodeJS Golang React Redis Android Ionic/Cordova Framework XML, HTML, CSS, Sass, Less jQuery, Bootstrap MongoDB SQLite, Postgres &amp; MySQL Git, Github, Bitbucket &amp; Gitlab Linux Agile Development Unit Testing

Updated on June 07, 2022

Comments

  • CommonSenseCode
    CommonSenseCode almost 2 years

    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"

  • Mistalis
    Mistalis about 7 years
    From the question: "Is there is any useful module to remove the unneeded URL parameters without having to use regex".
  • HoangHieu
    HoangHieu about 7 years
    Opps. that my mistake.
  • Cocowalla
    Cocowalla over 5 years
    Worth mentioning that this isn't supported in Internet Explorer
  • georgeawg
    georgeawg over 5 years
    One URLSearchParams polyfill -- github.com/jerrybendy/url-search-params-polyfill
  • CommonSenseCode
    CommonSenseCode over 5 years
    you shouldn't install an npm library just for that. Npm libraries are full of sub dependencies that introduce vulnerabilities into your code.
  • moto
    moto over 5 years
    You asked for a module... @commonSenseCode It's also easy to see what dependencies a package installs and to look at the code of the module to see if it is bigger than it needs to be.