4 examples of 'regex for us phone number' in JavaScript

Every line of 'regex for us phone number' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your JavaScript code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
1function formatPhoneNumber(phoneNumberString: string) {
2 var cleaned = ("" + phoneNumberString).replace(/\D/g, "");
3 var match = cleaned.match(/^(1|)?(\d{3})(\d{3})(\d{4})$/);
4
5 if (match) {
6 var intlCode = match[1] ? "+1 " : "";
7 return [intlCode, "(", match[2], ") ", match[3], "-", match[4]].join("");
8 }
9
10 return phoneNumberString;
11}
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

42public getDigits(phone: string): string {
43 const numbers = phone.match(/\d+/g)
44 if (numbers === null) return ''
45 return numbers.join('')
46}
267function formatPhone(ph) {
268 var numbers = ph.replace(/\D/g, ''),
269 char = {
270 0: '(',
271 3: ') ',
272 6: ' - '
273 };
274 if (numbers.length !== 10) return false;
275 var ret = '';
276 for (var i = 0; i < numbers.length; i++) {
277 ret += (char[i] || '') + numbers[i];
278 }
279 return ret;
280}
40function isValidPhone(value) {
41 return /^[0-9]+$/ig.test(value)
42}

Related snippets