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.
<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");
});
You can replace ""
like so:
$(document).ready(function () {
$("#content a").each(function (){
$(this).attr('href', $(this).attr("href").replace("%20",""));
});
});
You'd be better off using the native javascript encodeURI function.
$(".row a").each(function(){
$(this).attr( 'href', encodeURI( $(this).attr("href") ) );
});
I know this is super late, but I found that the unescape()
method tends to work too...
@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
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"));
});