Search code examples
javascriptjquerywordpresscaptioncaptions

Repeat innerHTML.replace


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>

Solution

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