简体   繁体   中英

str.replace not functioning as expected

I am currently writing a function to check if a url param is in the url. If it is there I am removing it and if it is not yet there I will be adding it. Essentially toggling the param on button click. Here is what I have so far.

     var value1 = $(this).attr("value");
     var collectionUrl = window.location.href; 
      if (collectionUrl.includes($(this).attr("value")))  {
          console.log("removing:   "  + $(this).attr("value"));
          collectionUrl.replace(value1,"");
      }
      else {
          console.log("adding:   "  + $(this).attr("value"));
          collectionUrl = collectionUrl + $(this).attr("value")+"/";
        }
    ajaxLoadPage(collectionUrl);

When the value is absent the value is added the the url as expected. When the value is already present in the url, the if statement does work and it outputs "removing: " value

However the value in the url is not being removed. I feel like I am missing something.

Calling "abc".replace("b","D") does not change the "abc" but returns new string "aDc" so you need to store the result in your collectionUrl .

So call it like this collectionUrl = collectionUrl.replace(value1,"");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM