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.
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"));