简体   繁体   English

如何仅更改div内容中尚未链接的电话号码?

[英]How alter only the phone numbers in a div's content that aren't already links?

I need to find all the phone numbers in the textContent of a div and all its children and if they're not already made into links (eg by iOS Safari, or by the person who created the page's content), then make them into links. 我需要在div及其所有子级的textContent中找到所有电话号码,如果尚未将它们建立为链接(例如,通过iOS Safari或创建页面内容的人),则将它们设为链接。 I'm not sure how to find the phone number and find if it's already a link. 我不确定如何查找电话号码以及是否已经是链接。

The code I was using only allows for finding phone numbers in the innerHTML and wrapping in a link tag: 我使用的代码仅允许在innerHTML查找电话号码并包装在链接标记中:

div.innerHTML = div.innerHTML.replace( 
    /(\(\d{3}\)(-|\.)?\d{3}(-|\.)?\d{4}|\d{3}(-|\.)?\d{3}(-|\.)?\d{4}|[0-9]{10,10})/g,
    "<a href=\"tel:$1\">$1</a>"
);

but how do I figure out if it's wrapped in a link tag and skip it if it is? 但是我如何确定它是否包装在链接标记中,如果是,则跳过它?

How about this. 这个怎么样。

((\(\d{3}\)(-|\.)?\d{3}(-|\.)?\d{4}|\d{3}(-|\.)?\d{3}(-|\.)?\d{4}|[0-9]{10,10}))(?!["<])

That does a lookahead at the end to make sure that the next characters are not a quotation mark (like the href phone number), or a less than (like the end of your anchor tag). 这样做可以确保末尾的字符不是引号(例如href电话号码),也不是小于号(例如anchor标签的结尾)。

I solved it by adding a check at the end for the closing a tag or a quote (so it doesn't change the hrefs): 我解决它通过在年底收盘添加检查a标签或引用(所以它不会改变的HREF):

(?![\s]*(\<\/a>|"|'))

The whole regex: 整个正则表达式:

/(\(\d{3}\)(-|\.)?\d{3}(-|\.)?\d{4}|\d{3}(-|\.)?\d{3}(-|\.)?\d{4}|[0-9]{10,10})(?![\s]*(\<\/a>|"|'))/g

It also allows for white space between the phone number and closing tag. 它还允许在电话号码和结束标签之间留有空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM