Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Detect telephone number in a string and replace it with "tel:"

Part One:

So I wanted to create a function that detects a phone number in a string and converts it to a tel: link. I have a function that detects telephone numbers:

 function tel(str) {
return /^(1?\s?\(?[0-9]{3}\)?\s?[0-9]{3}\s?[0-9]{4})$/.test(str) || /^(1?\s?[0-9]{3}\-?\s?[0-9]{3}\-?\s?[0-9]{4})$/.test(str) || /^(1?\s?\({1}[0-9]{3}\){1}\s?[0-9]{3}\-?\s?[0-9]{4})$/.test(str);
}

And if you call:

console.log(tel("555-666-7777"));

It will return true. But if I have a string along with it, it would return false.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Example:

console.log(tel("Hi, my phone number is: 555-666-7777"));
// Output: false

How could I detect it with the string?

Part Two

Once it’s detected the phone number in the string, how could I wrap it in a tel: link?

Example:

console.log(tel("You can reach me at 444-555-6654"));
// Output: "You can reach me at <a href="tel:444-555-6654">444-555-6654</a>"

How could I make all of this possible?

>Solution :

function tel(str) {
  let match = str.match(/^(.*)(\d{3}\-\d{3}\-\d{4})$/);
  if (!match) return str;

  let text = match[1];
  let phone = match[2];
  return `${text}<a href="tel:${phone}">${phone}</a>`;
}

console.log(tel("555-666-777"));
console.log(tel("555-666-7777"));
console.log(tel("You can reach me at 444-555-6654"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading