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...

9
  • you can use another way. like stackoverflow.com/a/42704871/3921623 Commented May 26, 2018 at 8: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. Commented May 26, 2018 at 8:50
  • @TanvirHasan i tried use that solution but doesn't work Commented May 26, 2018 at 8: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 . Commented May 26, 2018 at 8:57
  • 1
    @HasanTeymoori Nope, see this fiddle. Commented May 26, 2018 at 9:10

3 Answers 3

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());
    
Sign up to request clarification or add additional context in comments.

Comments

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.

4 Comments

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 I agree, but I couldn't reproduce the problem and I would have liked the OP to comment this.
@TakitIsy thanks for your solution , but problem in pushState not solved . result in console currect perfectly but in url not pushed!
@Vasan oops i'm sorry , edit comment. give me a time for testing last post
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
}

1 Comment

If there two parameters, foobar and bar in URL, and you pass bar as key, it would replace both params.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.