简体   繁体   English

str.replace无法按预期运行

[英]str.replace not functioning as expected

I am currently writing a function to check if a url param is in the url. 我目前正在编写一个函数来检查url参数是否在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. 缺少该值时,将按预期方式添加该URL。 When the value is already present in the url, the if statement does work and it outputs "removing: " value 如果该值已经存在于网址中,则if语句可以正常工作,并输出“ removing:”值

However the value in the url is not being removed. 但是,不会删除url中的值。 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 . 调用"abc".replace("b","D")不会更改“ abc”,但会返回新字符串“ aDc”,因此您需要将结果存储在collectionUrl

So call it like this collectionUrl = collectionUrl.replace(value1,""); 因此像这样调用它collectionUrl = collectionUrl.replace(value1,"");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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