重复innerHTML.replace
我使用下面的代码使 WordPress 标题中的链接可链接。例如,它成功地将 http://google.com
转换为 google.com。但是当我在标题中放置多个网址时,它只会更改第一个网址。有没有办法让它在所有链接上重复该操作?
<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>
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
RegExp 默认情况下仅找到一个匹配项。
this.innerHTML = this.innerHTML.replace(new RegExp(" http://([^ ]*) ", "g"), " ;$1 ");
添加“g”标志执行全局匹配。
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.
试试这个:
/g 意味着这个正则表达式是全局的。
Try this instead:
the /g means that this regular expression is global.
对
RegExp
调用进行细微更改即可实现此目的:关键是
'g'
修饰符参数 -g
代表全局;换句话说:全部替换。以下是相关参考资料:http://www.w3schools.com/jsref/jsref_regexp_g.asp
A subtle change to your
RegExp
call should do it: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