问题
Is there a javascript library the can recognize phone numbers in a web page? Just like what skype did on their firefox plugin.
Or do you know a way on how to do it? Websites or any tutorial that do the same would be very helpful.
Your reply is greatly appreciated.
Best,
回答1:
Someone else may have a better way of doing this, but this seems to give you a link around each phone number.
I just used my simple regular expression, so you may want to substitute the one that Adam provided.
$(document).ready(function () {
$('*','body').each(function() {
$(this).html( $(this).html().replace(/(\d\d\d-\d\d\d-\d\d\d\d)/g,'<a href="#">$1</a>') );
});
});
Hope it helps.
EDIT:
It may work as well, or better, with this version.
$(document).ready(function () {
$('body').html( $('body').html().replace(/(\d\d\d-\d\d\d-\d\d\d\d)/g,'<a href="#">$1</a>') );
});
I don't know if there are any pitfalls, but seems to work with a fairly simple page.
回答2:
var makePhoneLinks = function()
{
var tNodes = [];
getTextNodes(document.body,false,tNodes,/(((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4})/ig);
var l = tNodes.length;
while(l--)
{
wrapNode(tNodes[l],/(((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4})/ig,"<a target='#'>$1</a>");
}
}
function getTextNodes(node, includeWhitespaceNodes,textNodes,match) {
if (node.nodeType == 3) {
if (includeWhitespaceNodes || !/^\s*$/.test(node.nodeValue)) {
if(match){
if(match.test(node.nodeValue))
textNodes.push(node);
}
else {
textNodes.push(node);
}
}
} else {
for (var i = 0, len = node.childNodes.length; i < len; ++i) {
getTextNodes(node.childNodes[i],includeWhitespaceNodes,textNodes,match);
}
}
}
function wrapNode(n,match,m) {
var temp = document.createElement('div');
if(n.data)
temp.innerHTML = n.data.replace(match, m);
else{
//whatever
}
while (temp.firstChild) {
n.parentNode.insertBefore(temp.firstChild,n);
}
n.parentNode.removeChild(n);
}
回答3:
To find matches within a string, you'll want to use a regular expression. This one (although somewhat lengthy) works pretty well:
^(1\s*[-\/\.]?)?(\((\d{3})\)|(\d{3}))\s*[-\/\.]?\s*(\d{3})\s*[-\/\.]?\s*(\d{4})\s*(([xX]|[eE][xX][tT])\.?\s*(\d+))*$
(found here)
This will match "2405525009", "1(240) 652-5009", and "240/752-5009 ext.55", but not "(2405525009" or "2 (240) 652-5009".
To find all matches, you may want to repeatedly apply the exec()
method in a while
loop, as seen here.
来源:https://stackoverflow.com/questions/2807113/phone-number-recognition-in-javascript