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

javascript - How to replace more than once? - Stack Overflow

programmeradmin4浏览0评论

This is my code so far:

$("h1.intro:contains('|')").each(function() {
    $(this).html($(this).html().replace('|','</span><br /><span>')) 
});

This works just once, but it has to work for all of those "|"...

any ideas?

This is my code so far:

$("h1.intro:contains('|')").each(function() {
    $(this).html($(this).html().replace('|','</span><br /><span>')) 
});

This works just once, but it has to work for all of those "|"...

any ideas?

Share Improve this question edited Oct 19, 2010 at 18:19 slolife 19.9k20 gold badges79 silver badges126 bronze badges asked Oct 19, 2010 at 18:02 ThomaszterThomaszter 1,4741 gold badge13 silver badges26 bronze badges 1
  • 1 Note that replace() is a javascript call and is not part of jQuery – slolife Commented Oct 19, 2010 at 18:20
Add a ment  | 

3 Answers 3

Reset to default 14

Add /g modifier:

$("h1.intro:contains('|')").each(function() {
    $(this).html($(this).html().replace(/\|/g, '</span><br /><span>'));
});

More Info:

The g modifier is used to perform a global match (find all matches rather than stopping after the first match).

  • http://www.w3schools./jsref/jsref_regexp_g.asp

If you are using jQuery 1.4, you can do this more nicely using the .html(function)) signature:

$("h1.intro:contains('|')").each(function() {
    $(this).html(function(idx, oldContent) {
        return oldContent.replace(/\|/g, '</span><br /><span>');
    });
});

This means you don't have to create a second jQuery instance and should perform better.

Hi add a modifier to your regex by adding the "/g" after "|"

$("h1.intro:contains('|')").each(function() {
    $(this).html($(this).html().replace("|/g",'</span><br /><span>')) 
});
发布评论

评论列表(0)

  1. 暂无评论