views:

3176

answers:

6

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.

+5  A: 

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");
});
Jed Schmidt
Just a note since I was beating my head trying to figure this out. I use the HTML Validator add-on for Firefox and it was still reporting whitespace in URI references. This is because the validator parses the page separately, *without* JavaScript.
T Pops
+3  A: 

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"));
});
CMS
+7  A: 

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

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

Hi ,

is there any way to replace the %20 with a space.. exactly in the oppsiteway?

Thanks in advance

Naresh

Naresh
$(".row a").each( function() { this.href = this.href.replace(/%20/g," "); });or better yet $(".row a").each(function(){ $(this).attr( 'href', decodeURI( $(this).attr("href") ) ); });
Alexsander Akers
This is not an answer to the question above. If you have another question, I'm sure creating a new question (instead of replying in an answer to another one) will get you better results.
T Pops
A: 

You can replace ""...

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

@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

Waqar Ahmad