【问题标题】:jQuery / Javascript replace <space> in anchor link with %20jQuery / Javascript 将锚链接中的 <space> 替换为 %20
【发布时间】:2010-10-25 15:00:08
【问题描述】:

我是 jQuery 新手,我正在尝试编写一些代码来浏览页面并重写锚链接 href 属性,以便删除空格并替换为 %20。

到目前为止我有:

$(".row a").each(function(){
  $(this).attr("href").replace(/\s/g,"%20");
});

我已经尝试了一些变体,但都没有运气。

【问题讨论】:

    标签: javascript jquery html replace


    【解决方案1】:

    最好使用原生 javascript encodeURI 函数。

    $(".row a").each(function(){
      $(this).attr( 'href', encodeURI( $(this).attr("href") ) );
    });
    

    【讨论】:

    • 好东西。之前没有遇到过encodeURI。为我节省了大量时间。
    【解决方案2】:

    您的方法是正确的,但您在替换后忘记设置新值。试试这个:

    $(".row a").each( function() {
       this.href = this.href.replace(/\s/g,"%20");
    });
    

    【讨论】:

    • 只是一个注释,因为我一直在努力解决这个问题。我使用 Firefox 的 HTML Validator 插件,它仍然在 URI 引用中报告空格。这是因为验证器单独解析页面,没有 JavaScript。
    【解决方案3】:

    你必须设置属性值(attr(key, value)),在你的代码中你只是读取它的值:

    $(".row a").each(function(){
      $(this).attr('href', $(this).attr("href").replace(/\s/g,"%20"));
    });
    

    【讨论】:

      【解决方案4】:

      @Naresh 是的,有一种方法,请参见下面的示例:

      编码后解码一个URI:


      <script type="text/javascript">
      
      var uri="my test.asp?name=ståle&car=saab";
      document.write(encodeURI(uri)+ "<br />");
      document.write(decodeURI(uri));
      
      </script>  
      

      上面代码的输出将是:


      my%20test.asp?name=st%C3%A5le&car=saab
      my test.asp?name=ståle&car=saab
      

      更多详情请访问here

      【讨论】:

        【解决方案5】:

        你可以像这样替换""

        $(document).ready(function () {
            $("#content a").each(function (){
                $(this).attr('href', $(this).attr("href").replace("%20",""));
            });
        });
        

        【讨论】:

          【解决方案6】:

          我知道这已经很晚了,但我发现unescape() 方法也很有效......

          【讨论】:

            【解决方案7】:

            在 ES2021 中使用 replaceAll()

             $(".row a").each( function() {
                    this.href = this.href.replaceAll('',"%20");
                });
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2012-05-07
              • 2010-10-12
              • 2019-04-12
              • 1970-01-01
              • 2016-02-20
              • 1970-01-01
              • 2011-04-28
              • 1970-01-01
              相关资源
              最近更新 更多