Using the regular expression and match method you can extract phone numbers from strings in JavaScript.
Let’s take three different patterns of number that you want to search.
- 10 digits
+
sign followed by 10 digits- (xxx)-xxxxxxX format
These patterns are matched with the following regex.
/[\+]?\d{10}|\(\d{3}\)\s?-\d{6}/
Example how to extract phone number from string in JavaScript
HTML Example code extract phone numbers from text in JS.
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
var txt = 'ABC123 XYZ02 9886991201'
var num1 = txt.match(/[\+]?\d{10}|\(\d{3}\)\s?-\d{6}/);
alert(num1);
</script>
</head>
<body>
</body>
</html>
Output:
The metacharacter \d searches for digits, which are also numbers. The match() method uses regular expressions to retrieve its results. When used the match() with \d, it returns the number.
Other solution: If you already know your string is a phone number, just replace all non-numeric characters to leave your phone number:
That way, it doesn’t matter what the format is, you always get the number.
If you don’t know your string has a phone number, and you’re just searching in the wild, you can use the RegEx’s in the other answers to read numbers from a string in JavaScript.
Do comment if you have any doubts and suggestions on this topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version