0

I have a function for removing the parameter from url.
this is my function :

function removeParameter(key) {
   let parameters = document.location.search;

   const regParameter = new RegExp('[?|&]' + key + "=([a-zA-Z0-9_-]+)");

   if (regParameter.test(parameters)){
       parameters = parameters.replace(regParameter , '')
   }

    window.history.pushState({}, '', parameters)}

when I call this function for the url like this
http://example.com/products?color=4&brand=apple

first call function for removing the brand is correct result
removeParameter('brand')
but another call this function for removing the color doesn't work correctly. actually when i want to removing the first parameter(key come's after ? mark) this function doesn't work...

Andrei Suvorkov
  • 5,559
  • 5
  • 22
  • 48
Hasan Teymoori
  • 192
  • 1
  • 15
  • you can use another way. like https://stackoverflow.com/a/42704871/3921623 – Tanvir Hasan May 26 '18 at 08:46
  • What do you mean by doesn't work correctly? For `color`, it gives `&brand=apple` as output for me, which seems correct for what your code is trying to do. – Vasan May 26 '18 at 08:50
  • @TanvirHasan i tried use that solution but doesn't work – Hasan Teymoori May 26 '18 at 08:56
  • @Vasan as i said for remove the `brand` result is correct but for removing the `key` after the ? mark , result doesn't correct for me . – Hasan Teymoori May 26 '18 at 08:57
  • Repeating "result isn't correct" or "doesn't work correctly" does no good. You'll need to state clearly what is the expected result and what is the actual result. As I've mentioned in my comment, `color` is the first parameter in your example and your code removes it correctly. – Vasan May 26 '18 at 09:00
  • @Vasan my result for removing the `brand key` is : http://example.com/products?color=4 and result for removing the color is : http://example.com/products?color=4 . color not remove. i don't know why not removing for me. – Hasan Teymoori May 26 '18 at 09:04
  • 1
    @HasanTeymoori Nope, see [this fiddle](https://jsfiddle.net/x1vqjrLt/). – Vasan May 26 '18 at 09:10
  • @Vasan you right , i consoled my function result now, and it's work correctly, actually problem is the pushState function. i don't know why new parameters not pushing to url. – Hasan Teymoori May 26 '18 at 09:14
  • @Vasan where is the problem? result in console is correct , but not in url :( – Hasan Teymoori May 26 '18 at 09:20

3 Answers3

1

Correct me if I'm wrong,
I made a working snippet out of your code, and it seems to work correctly.

If you run the snippet on a fresh new tab, it will add 2 urls in the tab history.
I also modified your regex to make it easier.

function removeParameter(key) {
  var parameters = url; // document.location.search; // TAKIT: modified for test
  const regParameter = new RegExp('[?|&]' + key + "=([^&]+)"); // TAKIT: Simplified regex
  if (regParameter.test(parameters)) {
    parameters = parameters.replace(regParameter, '')
  }
  window.history.pushState({}, 'Test 1', parameters);
  return parameters; // TAKIT: Added
}

// Output 
var url = "https://stacksnippets.net/js?color=4&brand=apple";
console.log(url);
url = removeParameter("brand");
console.log(url);
url = removeParameter("color");
console.log(url);

Hope it helps.

Takit Isy
  • 9,688
  • 3
  • 23
  • 47
  • This isn't an answer though - because it doesn't provide a solution, basically just repeats OP's code. Would be better as a comment with a fiddle. – Vasan May 26 '18 at 09:13
  • @Vasan I agree, but I couldn't reproduce the problem and I would have liked the OP to comment this. – Takit Isy May 26 '18 at 09:16
  • @TakitIsy thanks for your solution , but problem in pushState not solved . result in console currect perfectly but in url not pushed! – Hasan Teymoori May 26 '18 at 10:14
  • @Vasan oops i'm sorry , edit comment. give me a time for testing last post – Hasan Teymoori May 26 '18 at 10:19
1

The third argument to pushState() is the entire URL. Your function is sending only the location.search i.e. query parameter part of the URL. So you'll need to do

window.history.pushState({}, '', location.pathname + parameters)}

on your function's last line. Also, your code is currently not handling the edge cases i.e. if you remove first parameter, it removes the ? and not the trailing &. So you end up with http://example.com/products&brand=apple which isn't a valid URL. And finally, I simplified your expression a bit.

const reg = new RegExp('[?&](' + key + '=[\\w-]+&?)');
let matches = reg.exec(parameters);
if (matches){
     parameters = parameters.replace(matches[1], '');
}

This still doesn't handle more complex cases (params without values, hash etc). There are a couple of other options:

  1. Dump the regex and go with a split('&') based solution. More code, but a lot more readable and less error-prone.
  2. If you don't need IE support, use URLSearchParams. Then your entire function can be reduced to this:

    var params = new URLSearchParams(location.search);
    params.delete(key);
    window.history.pushState({}, '', location.pathname + "?" +  params.toString());
    
Vasan
  • 4,810
  • 4
  • 20
  • 39
0

This function can be used, i modified @Takit Isy answer

function removeParameter(key) {
    var parameters = url; // document.location.search; // TAKIT: modified for test
    const regParameter = new RegExp(key + "=([a-zA-Z0-9_-]+[&]{0,1})");
    if (regParameter.test(parameters)) {
        parameters = parameters.replace(regParameter, '')
        if(parameters.substring(parameters.length-1)=='?' || parameters.substring(parameters.length-1)=='&'){
            parameters = parameters.slice(0, -1);
        }
    }
    return parameters; // TAKIT: Added
}
  • If there two parameters, foobar and bar in URL, and you pass bar as key, it would replace both params. – Vasan May 26 '18 at 09:54