jQuery / Javascript replace <space> in anchor link with %20

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.

Answers:

Answer

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

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

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

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

@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

Answer

You can replace "" like so:

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

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.