const regex = /(?>\G(?!^)|^(?:.*?[^\p{P}\h\d\n])?[\p{P}\h]*+1?(?=(?1){10}(?!(?1))))((\d)[\p{P}\h]*+)(?:[^\d\n].*)?/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?>\\G(?!^)|^(?:.*?[^\\p{P}\\h\\d\\n])?[\\p{P}\\h]*+1?(?=(?1){10}(?!(?1))))((\\d)[\\p{P}\\h]*+)(?:[^\\d\\n].*)?', 'gm')
const str = ` +18005551212
8005551213
18005551214
(800)555-1215
800.555.1216
(800) 555-1217
800 555 12 18
stuff before +18005551221 stuff after
stuff before 8005551222 stuff after
stuff before 18005551223 stuff after
stuff before (800)555-1224 stuff after
stuff before 800.555.1225 stuff after
stuff before (800) 555-1226 stuff after
stuff before 800 555 12 27 stuff after
5551212`;
const subst = `$2`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
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