Jquery replace for each

16,680

Solution 1

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>');
});

Solution 2

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

Solution 3

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

Share:
16,680

Related videos on Youtube

user1299846
Author by

user1299846

Updated on September 15, 2022

Comments

  • user1299846
    user1299846 over 1 year

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