In a NodeJS application, I have a phone number field in my data that displays any number of phone numbers, one after another, in the same string:
\n\n \n (555) 555-5555 (Main)\n\n, \n\n \n (777) 777-777 (Domestic Fax)\n\n
I want to extract only the 'Main' phone number and convert it to the format 555-555-5555, that is whatever the Main number is. Basically I just want to extract whatever number precedes 'Main' and make it more legible (replacing the space with the '-')
I got as far as finding the correct regex string
const phoneRegex = /^[ \\n]*\(([0-9]{3})\)( )([0-9]{3}-[0-9]{4}) \(Main\).*$/
but when I try to replace the string, it doesn't work
foo.phone =foo.phone.replace(phoneRegex,'$1-$3')
I keep getting the entire matched portion -- that is all the \n's and everything up to and including '(Main)'
I have searched for how to replace the entire string with the capture groups, but I haven't figured it out.
replace– you can extract a match first (seeRegExp#execorString#match), then create a new string from that.s.replace(/^\s*\((\d{3})\)\s*(\d+)-(\d+)[^]*$/, '$1-$2-$3'), I believe the\nare the newline chars in your sample string (you must have copied/pasted the string literal value from the console rather than shared the literal text).^\s*with^[^]*?