FidoBoy
FidoBoy

Reputation: 392

Replace all <a> tags in HTML string

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

Answers (4)

d_inevitable
d_inevitable

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);
     }
  });
}

See jsfiddle

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);
    }
});

See jsfiddle

Or you can use jQuery:

$("a[href]").click(function (event) {
   event.preventDefault();
   openLink($(this).attr("href"));
});

See jsfiddle

Upvotes: 1

Uri Agassi
Uri Agassi

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')\"");

http://regex101.com/r/wN0aB2


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')\"");

http://regex101.com/r/bZ0nO4

Upvotes: 3

stackErr
stackErr

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

Pedro Lobito
Pedro Lobito

Reputation: 98961

result = subject.replace(/<a.*?href="(.*?)".*?>(.*)<\/a>/img, "<a href=\"#\" onclick=\"openLink('$1')\">$2</a>");

http://regex101.com/r/dK2oU5

Upvotes: 0

Related Questions