1

I'm using the code below to make links linkable in WordPress captions. For example it successfully turns http://google.com into google.com. But when I put multiple url's in a caption it only changes the first one. Is there a way to make it repeat the action on all the links?

<script type="text/javascript">
    jQuery().ready(function() {
    jQuery("p.wp-caption-text").each(function(n) {
        this.innerHTML = this.innerHTML.replace(new RegExp(" http://([^ ]*) "), " <a href=\"http://$1\">$1</a> ");
    });
    });
</script>
ryanve
  • 50,076
  • 30
  • 102
  • 137

3 Answers3

2

A subtle change to your RegExp call should do it:

    jQuery().ready(function() {
        jQuery("p.wp-caption-text").each(function(n) {
            $(this).html($(this).html().replace(new RegExp(" http://([^ ]*) ", 'g'), " <a href=\"http://$1\">$1</a> "));
        });
    });

The key is the 'g' modifier argument -- g stands for global; in other words: replace all.

Here's the relevant reference material: http://www.w3schools.com/jsref/jsref_regexp_g.asp

namuol
  • 9,816
  • 6
  • 41
  • 54
2

RegExp by default only finds one match.

this.innerHTML = this.innerHTML.replace(new RegExp(" http://([^ ]*) ", "g"), " <a href=\"http://$1\">$1</a> ");

Adding the "g" flag performs a global match.

Jared
  • 12,406
  • 1
  • 35
  • 39
2

Try this instead:

this.innerHTML = this.innerHTML.replace.replace(/http:\/\/([^ ]*)/g, " <a href=\"http://$1\">$1</a> ");

the /g means that this regular expression is global.

Bernardo Mendes
  • 1,220
  • 9
  • 15