Reputation: 392
Let's suppose that I have an HTML string containing some <a href="..">
tags. How can I replace all of them to translate this:
<a href="http://www.mylink.com">whatever</a>
into this:
<a href="#" onclick="openLink('http://www.mylink.com')">whatever</a>
Any ideas?
Upvotes: 2
Views: 4263
Reputation: 4461
Don't use RegExp, because it is very hard, if not impossible, to safely restrict the matches to just the anchor links that you are targeting. Instead you should use the very DOM parser that naturally every browser has built in.
And don't use onclick
html attributes, because there is no need to tweak html in javascript to add javascript event handlers and it prevents users from using things like right click -> 'open in new tab', or 'copy link address'.
Use this:
var anchors = document.getElementsByTagName("a");
for (var i = 0 ; i != anchors.length ; i++) {
anchors[i].addEventListener("click", function (event) {
var href = this.getAttribute("href");
if (href) {
event.preventDefault();
openLink(href);
}
});
}
Or you can use a delegated event handler:
function openLink(href) {
alert("openLink " + href);
}
document.addEventListener("click", function (event) {
if (event.target.tagName === "A" && event.target.href) {
event.preventDefault();
openLink(event.target.href);
}
});
Or you can use jQuery:
$("a[href]").click(function (event) {
event.preventDefault();
openLink($(this).attr("href"));
});
Upvotes: 1
Reputation: 37409
You can use this regex on your string:
var re = new RegExp("<a href=\"([^\"]+)\"", "g");
result =
string.replace(re,
"<a href=\"#\" onclick=\"openLink('$1')\"");
Update
To account for attributes before the href
, you could use:
var re = new RegExp("<a([^>]* )href=\"([^\"]+)\"", "g");
result =
string.replace(re,
"<a$1href=\"#\" onclick=\"openLink('$2')\"");
Upvotes: 3
Reputation: 4170
You can easily do this using JS.
Find all anchor elements in DOM and setAttributes:
var anchors = document.getElementsByTagName("a");
for(var i =0; i < anchors.length; i++)
{ var myLink = anchors[i].getAttribute("href");
anchors[i].setAttribute("href","#");
anchors[i].setAttribute("onclick", "openLink('"+ myLink +"');");
}
Upvotes: 1
Reputation: 98961
result = subject.replace(/<a.*?href="(.*?)".*?>(.*)<\/a>/img, "<a href=\"#\" onclick=\"openLink('$1')\">$2</a>");
Upvotes: 0