重复innerHTML.replace

| 我正在使用下面的代码来使链接在WordPress标题中可链接。例如,它将“ 0”成功转换为google.com。但是,当我在标题中放入多个url \时,它只会更改第一个。有没有办法让它在所有链接上重复操作?
<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>
    
已邀请:
默认情况下,RegExp只找到一个匹配项。
this.innerHTML = this.innerHTML.replace(new RegExp(\" http://([^ ]*) \", \"g\"), \" <a href=\\\"http://$1\\\">$1</a> \");
添加\“ g \”标志执行全局匹配。     
尝试以下方法:
this.innerHTML = this.innerHTML.replace.replace(/http:\\/\\/([^ ]*)/g, \" <a href=\\\"http://$1\\\">$1</a> \");
/ g表示此正则表达式是全局的。     
对您的
RegExp
通话进行微妙的更改即可:
    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> \"));
        });
    });
关键是
\'g\'
修饰符参数
g
代表全局;换句话说:全部替换。 这是相关的参考资料:http://www.w3schools.com/jsref/jsref_regexp_g.asp     

要回复问题请先登录注册