Learn how to extract phone numbers from string in JavaScript

Extracting phone numbers from strings is one way to clean up data that you might have collected. This tutorial will show you how to extract phone numbers using JavaScript.

This tutorial teaches the basics of extracting a phone number from a string in JavaScript and is designed for people who are not experienced with programming. Find the steps below to get the phone numbers from the string.

Step One: Declare the variables:

const string = 'test1 +91 9443134651 test2 +1 671-765-0091';
let phone_numbers = []

The first line creates a new variable called string and sets static text with phone numbers. The second line creates an empty array called phone_numbers which will be used to store any retrieved phone numbers.

Step Two: Add the JavaScript regex expression

In JavaScript, you can use the RegExp to find out if a string matches a regular expression or not.

The below regex expression is used for extracting the phone number from a text string. Regexp object has five methods: test(), exec(), search(), match() and matchAll(). Declare the “regexp“ variable and assign the RegExp.

const regexp = new RegExp("\\+?\\(?\\d*\\)? ?\\(?\\d+\\)?\\d*([\\s./-]?\\d{2,})+","g");

Step Three: Use exec() or matchAll() to get all matched phone numbers

Demo using matchAll() function

See the Pen Extract Phone Numbers from a String Using JavaScript matchAll() by Vimalraj (@w3tweaks) on CodePen.

Demo using exec() function

See the Pen Extract Phone Numbers from a String Using JavaScript RegExp.exec() by Vimalraj (@w3tweaks) on CodePen.

Different between matchAll() vs exec() in JavaScript

What is JavaScript matchAll() function?

The JavaScript matchAll() function is used to find all the matches of a given expression and return an array of those matches. The matchAll() method is a new JavaScript String function that will return an iterator that returns all matched groups against a regular expression, including capturing groups. The purpose of this method is to have better access to information about the matched groups.

What is JavaScript exec()?

JavaScript exec() is a method of the RegExp object that executes a regular expression and returns an array of matches, or null if there are no matches.

Warning

Do not place the regular expression literal within the 'while' condition! find the details in the link.

W3TWEAKS
Latest posts by W3TWEAKS (see all)

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *