Keith Morris
Keith Morris

Reputation: 2175

JavaScript Regex to Match Phone numbers but not in HTML attributes

We're needing a match phone numbers in some chunks of HTML with JavaScript and are very close but are having problems. We don't want to match phone numbers that show up in attributes such as max-length="404-555-1212". Consider the following text:

Sample:

Shouldn’t Match:
max-length='0123456789'
max-length="0123456789"
max-length=012-345-6789"

Don’t want the >
<strong>866.643.4170</strong>

Don’t really want this plus included either:
+1-(800)-555-2468

abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789 +-.,!@#$%^&*();\/|<>"'
12345 -98.7 3.141 .6180 9,000 +42
555.123.4567     +1-(800)-555-2468

With the following Regex, we are able to grab all of the phone numbers but it does not exclude the attributes:

/(\d{1}[-. ])?\(?\d{3}\)?[-. ]? *\d{3}-? *[-. ]?\d{4}/g

We tried the following but it is leaving the > at the end of <strong>:

/[^"='](\d{1}[-. ])?\(?\d{3}\)?[-. ]? *\d{3}-? *[-. ]?\d{4}/g

Any thoughts on how to make this work?

Upvotes: 1

Views: 125

Answers (1)

Keith Morris
Keith Morris

Reputation: 2175

So someone answered this question yesterday and I was coming back to accept the answer but it had been removed. However, the solution that they provided did work so, for posterity, I wanted to post the solution that they had given.

Here is the regex that solves the problem:

/(?:\d[-. ])?\(?\d{3}\)?[-. ]?\d{3}[-. ]?\d{4}(?!["'])/g

And here is a link to the working example:

http://regex101.com/r/rK6wY1/1

I wish I could have given credit to the original answerer.

Upvotes: 1

Related Questions