benhowdle89
benhowdle89

Reputation: 37464

Javascript replace has no effect

This is the jQuery:

<script type="text/javascript">
    $(document).ready(function(){
        var relName;
        $('.child').each(function() {
            relName = $(this).attr('rel');
            relName.replace('&','');
            $(this).attr('rel', relName);
            $(this).appendTo('#' + $(this).attr('rel'));
        });
    }); 
</script>

With this relevant HTML:

<div rel="MadDogs&EnglishmenHandpaintedfigurines" id="Figurines" class="category section child">
     <h3 class="categoryTitle">Figurines</h3>               
</div>

But for some reason, the replace has no effect whatsoever!

Upvotes: 1

Views: 303

Answers (4)

Eric
Eric

Reputation: 97591

Here's a neat way to write it, using the callback version of attr basically every jQuery method:

$(document).ready(function() {
    $('.child').attr('rel', function(i, relName) {
        $(this).appendTo('#' + relName);
        return relName.replace('&','');
    });
}); 

Upvotes: 2

James Johnson
James Johnson

Reputation: 46047

It's not updating because you're not assigning the result to anything.

Try this instead:

$(this).attr('rel', relName.replace('&',''));

Upvotes: 2

Niko
Niko

Reputation: 26730

replace() doesn't change the original string, it returns a new one.

Upvotes: 3

Samich
Samich

Reputation: 30115

replace returns string with replaced data. So you need to assign back to your variable.

relName = relName.replace('&','');

Upvotes: 8

Related Questions