JSFiddle - React, Tailwind, and code Playground
HTML
<div id="departments">
<ul>
<li>Department 1 - (555) 123-1234</li>
<li>Department 2 - (555) 123-4321</li>
<li>Department 3 - (555) 123-6789</li>
</ul>
</div>
<input type='text' value='(555) 123-6789' />
<a href='(555) 123-6789'>(555) 123-6789</a>
JavaScript
var regex = /((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}/g;
var text = $("body:first").html();
var textNodes = $("body:first").find('*').contents().filter(function(){
if(this.nodeType == 3 && regex.test(this.nodeValue) && this.parentElement.tagName !== "A"){
var anchor = document.createElement('a');
anchor.setAttribute('href', this.nodeValue.match(regex)[0]);
anchor.appendChild(document.createTextNode(this.nodeValue.match(regex)[0]));
if(this.nextSibling)
this.parentElement.insertBefore(anchor, this.nextSibling);
else
this.parentElement.appendChild(anchor);
this.nodeValue = this.nodeValue.replace(regex, '');
}
return this.nodeType == 3;
});
console.log(textNodes);
//text = text.replace(regex, "<a href=\"tel:$&\">$&</a>");
//$("body:first").html(text);