find phone numbers in a string using regex in javascript

To find phone numbers in a string using regex in Javascript, you can use the following code:

index.tsx
const phoneNumberRegex = /((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}/g;
const str = "Please call (555) 555-5555 or 555-555-5555 for assistance.";

const phoneNumbers = str.match(phoneNumberRegex);
console.log(phoneNumbers); // ["(555) 555-5555", "555-555-5555"]
256 chars
6 lines

In the code above, we define a regular expression phoneNumberRegex that matches phone numbers in the formats (123) 456-7890 or 123-456-7890. We then use the match() method on the string str to find all matches of the regular expression and return them in an array. Finally, we log the array of phone numbers to the console.

Note that this regular expression may not match all possible phone number formats and may also match non-phone number strings. It's important to thoroughly test and validate your regular expression to ensure it meets your specific requirements.

gistlibby LogSnag