最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery replace for each - Stack Overflow

programmeradmin4浏览0评论

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

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>"));
        });
Share Improve this question asked Jul 4, 2012 at 23:02 user1299846user1299846 3873 gold badges8 silver badges16 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 7

Regex : Working Demo http://jsfiddle/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>"));
      //      });

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

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>');
});
发布评论

评论列表(0)

  1. 暂无评论