Just a rough idea.
// ['Initial match', 'Pattern to grab from match', 'function to replace with']
var matches = {
f1 : ["\\\\d{10}", "(\\\\d{3})(\\\\d{3})(\\\\d{4})", function(a, n1, n2, n3){return "("+n1+") "+n2+"-"+n3;}],
f2 : ["\\\\d{11}", "(\\\\d{3})(\\\\d{4})(\\\\d{4})", function(a, n1, n2, n3){return n1+' - '+n2+' - '+n3;}]
};
var numberCheck = function(node, mtches){
var result = [],
regMtch = new RegExp(mtches[0]), // Initial match
regRep = new RegExp(mtches[1]), // To replace pattern
matchFn = mtches[2]; // With
var check = function(text){
var mtch = text.match(regMtch);
if (mtch) result.push(mtch[0].replace(regRep, matchFn));
};
(function walkDom(node){
if (node.nodeType === 3 && !/\
/.test(node.nodeValue)) check(node.nodeValue);
node = node.firstChild;
while (node){
walkDom(node);
node = node.nextSibling;
}
}(node))
return result;
};
Test:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Num Check</title>
</head>
<body>
<p>What are you planning to do with my number 9546302299?</p>
<ul>
<li>9546302299</li>
<li>0207696969</li>
<li>02082224444</li>
<li>0208969669</li>
<li>4596203922</li>
</ul>
<script type="text/javascript">
// ['Initial match', 'Pattern to grab from match', 'function to replace with']
var matches = {
f1 : ["\\\\d{10}", "(\\\\d{3})(\\\\d{3})(\\\\d{4})", function(a, n1, n2, n3){return "("+n1+") "+n2+"-"+n3;}],
f2 : ["\\\\d{11}", "(\\\\d{3})(\\\\d{4})(\\\\d{4})", function(a, n1, n2, n3){return n1+' - '+n2+' - '+n3;}]
};
var numberCheck = function(node, mtches){
var result = [],
regMtch = new RegExp(mtches[0]), // Initial match
regRep = new RegExp(mtches[1]), // To replace pattern
matchFn = mtches[2]; // With
var check = function(text){
var mtch = text.match(regMtch);
if (mtch) result.push(mtch[0].replace(regRep, matchFn));
};
(function walkDom(node){
if (node.nodeType === 3 && !/\
/.test(node.nodeValue)) check(node.nodeValue);
node = node.firstChild;
while (node){
walkDom(node);
node = node.nextSibling;
}
}(node))
return result;
};
console.log(numberCheck(document, matches.f1));
// ["(954) 630-2299", "(954) 630-2299", "(020) 769-6969", "(020) 822-2444", "(020) 896-9669", "(459) 620-3922"]
</script>
</body>
</html>