jQuery / Javascript replace in anchor link

2019-02-13 00:01发布

问题:

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.

so far i have:

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

I've tried a few variations of this with no luck.

回答1:

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");
});


回答2:

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

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


回答3:

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"));
});


回答4:

@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



回答5:

You can replace "" like so:

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


回答6:

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