-1

i'm struggling with some magic. I'm trying to remove parametr value from URL on click:

 function removeParam(name, value) {
    var newUrl = window.location.href.split("?")[0],
            sourceURL = window.location.href,
    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.indexOf(name) !== -1) {
            if (params_arr[i].indexOf("%s") !== -1) {
                params_arr[i] = param.replace("%s" + value , "");
                params_arr[i] = param.replace(value , "");

            }
            else {
                params_arr[i] = param.replace(name + "=" + value, "");
            }
        }
    }
    if (params_arr[0] !== "") {
        newUrl = newUrl + "?" + params_arr.join("&");
    }

}
window.history.pushState(null,"", newUrl);

Remove value C from var
Source URL: /?var=A%sB%sC
URL-should-be: /?var=A%sB

I can have multiple parameters with corresponding values like Source URL: /?var=A%sB%sC&var2=D%sE%sF

But magic is that if i add second str: params_arr[i] = param.replace(value , ""); It will remove only C without separator: %s

How to fix it ?

I added this second replace because i need to remove values from head.

Scorpa
  • 1
  • 1
  • So you want to get the URL value? What about the [Location](https://developer.mozilla.org/en-US/docs/Web/API/Location) object? – Ron van der Heijden Mar 14 '17 at 17:43
  • I know how to do it :) I just dont understand why if i add another str.replace it will add separator. In debugger i can see that second str.replace do nothing but on the next step it magicly adding separator without any reason – Scorpa Mar 14 '17 at 17:51

1 Answers1

0

this has been answered before, try this

function removeURLParameter(url, parameter) {
    //prefer to use l.search if you have a location/link object
    var urlparts= url.split('?');   
    if (urlparts.length>=2) {

        var prefix= encodeURIComponent(parameter)+'=';
        var pars= urlparts[1].split(/[&;]/g);

        //reverse iteration as may be destructive
        for (var i= pars.length; i-- > 0;) {    
            //idiom for string.startsWith
            if (pars[i].lastIndexOf(prefix, 0) !== -1) {  
                pars.splice(i, 1);
            }
        }

        url= urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : "");
        return url;
    } else {
        return url;
    }
}

https://stackoverflow.com/a/1634841/3511012

Community
  • 1
  • 1
stackoverfloweth
  • 5,753
  • 3
  • 33
  • 57