Jim Hyland
Jim Hyland

Reputation: 239

Javascript replace for all instances

I found a nice bit of code to add some 'normal' text links (i.e. rather than a button) to share a page on social media sites:

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

Which works great. But for Pinterest I need the url to placed twice, for the page url and for the pin image:

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

In this case just the first url gets added.

Not that hot on javascript. There must be an easy way to replace all instances of [url], right?

Upvotes: 1

Views: 138

Answers (2)

jimr
jimr

Reputation: 11230

Use a regex with the g (global) modifier

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

Upvotes: 2

Trevor
Trevor

Reputation: 9578

Use a global regexp to match them all:

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

Upvotes: 1

Related Questions