views:

252

answers:

3

I want to add a call to a onclick event in any href that includes a mailto: tag.

For instance, I want to take any instance of:

<a href="mailto:[email protected]">

And change it into:

<a href="mailto:[email protected]" onclick="return function();">

The problem that I'm having is that the value of the mailto string is not consistent.

I need to say something like replace all instances of the '>' character with ' onclick="return function();">' in strings that match '<a href="mailto:*">' .

I am doing this in ColdFusion using the REreplacenocase() function but general RegEx suggestions are welcome.

+2  A: 

If the only purpose of this is to add a JavaScript event handler, I don't think Regex is the best choice. If you use JavaScript to wire up your JavaScript events, you'll get more graceful degradation if JS is not available (e.g. nothing will happen, instead of having onclick cruft scattered throughout your markup).

Plus, using the DOM eliminates the possibility of missing matches or false positives that can occur from a Regex that doesn't perfectly anticipate every possible markup formation:

function myClickHandler() {
    //do stuff
    return false;
}

var links = document.getElementsByTagName('a');
for(var link in links) {
    if(link.href.indexOf('mailto:') == 0) {
        link.onclick = myClickHandler;
    }
}
Rex M
+2  A: 

The following will add your onclick to all mailto links contained withing a string str:

REReplaceNoCase(
    str,
    "(<a[^>]*href=""mailto:[^""]*""[^>]*)>",
    "\1 onclick=""return function();"">",
    "all"
)

What this regular expression will do is find any <a ...> tag that looks like it's an email link (ie. has an href attribute using the mailto protocol), and add the onclick attribute to it. Everything up to the end of the tag will be stored into the first backreferrence (referred to by \1 in the replacement string) so that any other attributes in the <a> will be preserved.

Daniel Vandersluis
+1  A: 

Why wouldn't you do this on the frontend with a library like jQuery?

$(function(){
 $("a[href^=mailto]").click(function(){
  // place the code you want to execute here
 })
});
rip747