Javascript 替换所有实例

Javascript replace for all instances

本文关键字:实例 替换 Javascript      更新时间:2023-09-26

我找到了一些很好的代码来添加一些"普通"文本链接(即而不是按钮)以在社交媒体网站上共享页面:

<a href="https://twitter.com/share?url=[url]"onclick="this.href = this.href.replace('[url]',window.location)" target="_blank" title="Share on Twitter">Twitter</a>

效果很好。但是对于Pinterest,我需要放置两次网址,页面网址和固定图像:

<a href="http://pinterest.com/pin/create/button/?url=[url]&media=[url]pin.jpg" onclick="this.href = this.href.replace('[url]',window.location)" target="_blank">Pinterest</a>

在这种情况下,只添加第一个 url。

在javascript上不是那么热。一定有一个简单的方法来替换[url]的所有实例,对吧?

使用带有

g(全局)修饰符的正则表达式

this.href.replace(/'[url']/g, window.location)

使用全局正则表达式来匹配它们:

this.href = this.href.replace(/'[url']/g, window.location)