简体   繁体   中英

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?

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

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

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 +"');");
}
result = subject.replace(/<a.*?href="(.*?)".*?>(.*)<\/a>/img, "<a href=\"#\" onclick=\"openLink('$1')\">$2</a>");

http://regex101.com/r/dK2oU5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM