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>

Related posts

Leave a Reply

3 comments

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

  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.

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