JSFiddle - React, Tailwind, and code Playground
HTML
<strong>Demo created by gwnRob@gmail.com.</strong><br>
@Twitter, @ foo@bar bar@red example@example.com
<a href="http://stackoverflow.com/questions/12209628/is-there-a-chrome-extension-to-add-mailto-links-to-email-addresses">Link to Stack Overflow question with valid@example.com address (not wrapped)</a>
JavaScript
// Initiate recursion
wrapLink(document.body);
function wrapLink(elem) { // elem must be an element node
var nodes = elem.childNodes
, i = nodes.length
, regexp = /([-!\x23$%&'*+\/=?^_`{}|~0-9A-Z]+(\.[-!\x23$%&'*+\/=?^_`{}|~0-9A-Z]+)*|^"([\x01-\x08\x0b\x0c\x0e-\x1f!\x23-\\[\\]-\x7f]|\\[\x01-011\x0b\x0c\x0e-\x7f])*")@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}/i
, node, emailNode, a, result;
while (node = nodes[--i]) {
if (node.nodeType === 1) {
// Skip anchor tags, nested anchors make no sense
if (node.nodeName.toUpperCase() !== 'A')
wrapLink(node);
} else if (node.nodeType === 3) {
// 1: Please note that the regexp has NO global flag,
// and that `node.textContent` shrinks when an address is found
while (result = regexp.exec(node.textContent)) {
// 2: Contact <SPLIT> me@example.com for details
node = node.splitText(result.index);
// 2: Contact <SPLIT>me@example.com<SPLIT> for details
node = node.splitText(result[0].length);
// me@example.com
emailNode = node.previousSibling
// 3. Create link
a = document.createElement('a');
a.href = 'mailto:' + result[0];
// 4: Append emailNode
a.appendChild(emailNode);
// 5: Insert before
elem.insertBefore(a, node);
}
}
}
}