简体   繁体   中英

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. 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:

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).

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):

(?![\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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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