user1299846
user1299846

Reputation: 387

Jquery replace for each

I want to replace every "New" inside every link with span tag.

Is it right?

$("a:contains('New')").each(function () {
                 $(this).html($(this).html().replace("New", "<span class='new'>New</span>"));
        });

Upvotes: 3

Views: 18770

Answers (3)

graygilmore
graygilmore

Reputation: 1768

Here's a pretty simple method as well:

$("a:contains('New')").each(function() {
    $(this).html(function(index, text) {
        return text.replace('New', '<span class="new">New</span>');
    });
});

From here: JavaScript/jQuery: replace part of string?

Edit:

Ricardo Lohmann's answer is better, kills the each() function:

$("a:contains('New')").html(function(i, text) {
    return text.replace(/New/g, '<span class="new">New</span>');
});

Upvotes: 3

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

Have you tried your code ?
It's working well as you can see here, the only problem is that you forgot to use g modifier to replace all "New" ocurrences.

Other problem is that you don't need each loop, as you can see the following code do the same thing.
The difference is that it's not necessary to loop and get item html twice.

$("a:contains('New')").html(function(i, text) {
    return text.replace(/New/g, '<span class="new">New</span>');
});

demo

Upvotes: 4

Tats_innit
Tats_innit

Reputation: 34117

Regex : Working Demo http://jsfiddle.net/WujTJ/

g = /g modifier makes sure that all occurrences of "replacement"

i - /i makes the regex match case insensitive.

A good read: if you keen: http://www.regular-expressions.info/javascript.html

Please try this:

Hope this help :)

Also note you might not need to check if it contains New or not, because regex will change if need be:

   // $("a:contains('New')").each(function () { // NOT sure if you need this
                     $(this).html($(this).html().replace(/New/g, "<span class='new'>New</span>"));
      //      });

Upvotes: 7

Related Questions