const regex = /(?x)(
# phone number
(\+1)?
(\s)?
(\(\d\d\d\))? #area code optional
(\s|-) # first separator
\d\d\d # first 3 digits
- # Separator
\d\d\d\d # last 4 digits
)/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?x)(
# phone number
(\\+1)?
(\\s)?
(\\(\\d\\d\\d\\))? #area code optional
(\\s|-) # first separator
\\d\\d\\d # first 3 digits
- # Separator
\\d\\d\\d\\d # last 4 digits
)', 'gm')
const str = `+1 (786) 665-5397
+1 (786) 773-7145
+1 (786) 804-8869
+1 (786) 806-5097
+1 (786) 856-7950
+1 (786) 862-2875
+1 (786) 915-7830
+1 (786) 991-4304
+1 (857) 334-1162
+1 (862) 944-0090
+1 (863) 307-5291
+1 (914) 826-4343
+1 (918) 992-1382
+1 (954) 226-7037`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions