views:

62

answers:

3

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?

+8  A: 

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

Sarfraz
`replace(/\|/g, '</span><br/><span>')`, more correctly.
Chris
@Chris: Updated thanks :)
Sarfraz
the 'more correctly' works! I have to learn regular expressions, thx mates.
Thomasz
A: 

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>')) 
});
madsleejensen
You need to use a regex literal. JavaScript doesn't turn strings into regex literals on the fly.
BoltClock
+2  A: 

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.

lonesomeday
+1: Useful; I hadn't known about this invocation of .html() before. Good call!
Chris
Nice solution, and when ignore the second bracket ".replace(...))" it works like a charm. thank you.
Thomasz
Fixed, thanks..
lonesomeday