6

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
  • 17,793
  • 13
  • 73
  • 97
CommonSenseCode
  • 23,522
  • 33
  • 131
  • 186

7 Answers7

14

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.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
10

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

Community
  • 1
  • 1
Mistalis
  • 17,793
  • 13
  • 73
  • 97
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>
HoangHieu
  • 2,802
  • 3
  • 28
  • 44
2

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);
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

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'
moto
  • 946
  • 10
  • 27
  • you shouldn't install an npm library just for that. Npm libraries are full of sub dependencies that introduce vulnerabilities into your code. – CommonSenseCode Dec 21 '18 at 08:29
  • 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. – moto Dec 25 '18 at 18:44
0

Enhnaced @Mistalis's answer.

  1. Return the value of the last occurrence of a param
  2. Remove the ? of the removed param was the only param
  3. Url encoded the query params to ensure browser stately
function pruneParams(key, url) {
  var urlParts = url.split('?');
  var rtnUrl = urlParts[0];
  var paramParts;
  var paramValue;
  var params_arr = [];
  var queryString = decodeURIComponent(urlParts[1] || '');
  if (queryString !== '') {
    params_arr = queryString.split('&');
    for (var i = params_arr.length - 1; i >= 0; --i) {
      paramParts = params_arr[i].split('=');
      if (paramParts[0] === key) {
        paramValue = paramParts[1];
        params_arr.splice(i, 1);
      }
    }
    if (params_arr.length) {
      var wasEncoded = url.split('&').length < 2;
      rtnUrl = rtnUrl + '?' + (wasEncoded ? encodeURIComponent(params_arr.join('&')) : params_arr.join('&'));
    }
  }
  return { url: rtnUrl, [key]: paramValue, paramCount: params_arr.length > 1 };
}

var u1 = 'http://localhost:4200/member/';
var u2 = 'http://localhost:4200/member/?ts=23423424';
var u3 = 'http://localhost:4200/member/?fooo=2342342asfasf&ts=252523525';
var u4 = 'http://localhost:4200/member?foo=234243&ts=234124124&bar=21kfafjasf&ts=223424234&dd=This Is A Line';
var u5 = 'http://localhost:4200/member?foo%3D234243%26ts%3D2242424%26bar%3D21kfafjasf%26dd%3DThis%20Is%20A%20Line';

console.log(pruneParams('ts', u1));
console.log(pruneParams('ts', u2));
console.log(pruneParams('ts', u3));
console.log(pruneParams('ts', u4));
console.log(pruneParams('ts', u5));


//   {
//     url: 'http://localhost:4200/member/',
//     ts: undefined,
//     paramCount: false,
//   }
//   {
//     url: 'http://localhost:4200/member/',
//     ts: '23423424',
//     paramCount: false,
//   }
//   {
//     url: 'http://localhost:4200/member/?fooo=2342342asfasf',
//     ts: '252523525',
//     paramCount: false,
//   },
//   {
//     url: 'http://localhost:4200/member?foo=234243&bar=21kfafjasf&dd=This Is A Line',
//     ts: '234124124',
//     paramCount: true,
//   }
//   {
//     url: 'http://localhost:4200/member?foo%3D234243%26bar%3D21kfafjasf%26dd%3DThis%20Is%20A%20Line',
//     ts: '2242424',
//     paramCount: true,
//   }


Val Neekman
  • 17,692
  • 14
  • 63
  • 66
0

Taken from @Mistalis answer but tidied up. Useful if URLSearchParams API is not available.

const removeUrlParam = function (url, param) {

   var parts = url.split('?')
   
   url = parts[0]
   if (parts.length !== 2) return url
   
   var qs = parts[1]
   if (qs === '') return url

    var params = qs.split('&')
    for (var i = params.length - 1; i >= 0; i -= 1) {
      var key = params[i].split('=')[0]
      if (key === param) params.splice(i, 1)
    }

    return params.length ? url + '?' + params.join('&') : url
}

var url1 = removeUrlParam('/xxxxx', 'a')
var url2 = removeUrlParam('/xxxxx?a=1', 'a')
var url3 = removeUrlParam('/xxxxx?a=1&b=2', 'a')

console.log(url1, url2, url3)
danday74
  • 52,471
  • 49
  • 232
  • 283