jQuery / Javascript replace in anchor link with

后端 未结 6 1544
独厮守ぢ
独厮守ぢ 2021-01-04 23:49

I\'m new to jQuery and i\'m trying to write some code to go through the page and rewrite anchor links href attribute so that spaces are removed and replaced with %20.

<
相关标签:
6条回答
  • 2021-01-04 23:51

    Your approach is correct, but you're forgetting to set the new value once you replace it. Try this:

    $(".row a").each( function() {
       this.href = this.href.replace(/\s/g,"%20");
    });
    
    0 讨论(0)
  • 2021-01-04 23:51

    You can replace "" like so:

    $(document).ready(function () {
        $("#content a").each(function (){
            $(this).attr('href', $(this).attr("href").replace("%20",""));
        });
    });
    
    0 讨论(0)
  • 2021-01-04 23:57

    You'd be better off using the native javascript encodeURI function.

    $(".row a").each(function(){
      $(this).attr( 'href', encodeURI( $(this).attr("href") ) );
    });
    
    0 讨论(0)
  • 2021-01-05 00:05

    I know this is super late, but I found that the unescape() method tends to work too...

    0 讨论(0)
  • 2021-01-05 00:07

    @Naresh Yes there is a way for that, see the below example:

    Decode a URI after encoding it:


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

    The output of the code above will be:


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

    for more details visit here

    0 讨论(0)
  • 2021-01-05 00:09

    You have to set the attribute value ( attr(key, value) ), in your code you are only reading its value:

    $(".row a").each(function(){
      $(this).attr('href', $(this).attr("href").replace(/\s/g,"%20"));
    });
    
    0 讨论(0)
提交回复
热议问题