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.
HTML Example code extract phone numbers from text in JS.
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.
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
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.