JSFiddle - React, Tailwind, and code Playground
HTML
<div id="someBlockIWantToConvert">
<div>hey</div>
<a href="tel:123456789">1234556789</a>
<div>123456789</div>
</div>
JavaScript
// TODO exclude already matched detectors and move most greedy ones last
// TODO change the module to export a bit nicer.
var discoverAndLinkData = (function() {
var discoverAndLinkData = function(toDetect) {
var plainTextString = this;
console.log(toDetect);
toDetect = toDetect || {};
// International phone numbers are incredibly varied. This is designed
// to pick up numbers in many regions.
var phoneRegEX = /(\+\s?)?(\(\d{3}\)\s?)?((\d)([-.\s\\\/])?)+\b/g;
var httpRegEX = /\bhttp{1}s?:\/\/([-A-Z0-9+&@#\/%?=~_|!:,.;]*)+\b/gi;
var emailRegEX = /\b([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4})\b/gi;
// default true for phone like IOS
if (toDetect.phone || toDetect.phone === undefined) {
plainTextString = plainTextString.replace(phoneRegEX, function(match, content) {
if (match.replace(/\D/g, "").length >= 6) {
return "<a href='tel://" + match + "'>" + match + "</a>";
}
return match;
});
}
// TODO between each match exclude that text from matching again.
if(toDetect.email){
plainTextString = plainTextString.replace(emailRegEX, function(match, content) {
return "<a href='mailto:" + match + "'>" + match + "</a>";
});
}
if(toDetect.http){
plainTextString = plainTextString.replace(httpRegEX, function(match, content) {
return "<a href='" + match + "'>" + match + "</a>";
});
}
return plainTextString;
}
// This was adapted from some
function traverseTextNodes(node, callback, args) {
var next;
if(node){
if (node.nodeType === 1) {
// (Element node)
if (node = node.firstChild) {
do {
// Recursively call traverseChildNodes
...