javascript – How to replace more than once? – Education Career Blog

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?

,

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).

,

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

Leave a Comment