Replacing a substring using regular expressions


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

And change it into:

<a href="" 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.

Best Solution

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

    "\1 onclick=""return function();"">",

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.