【问题标题】:Detect telephone number in a string and replace it with "tel:"检测字符串中的电话号码并将其替换为“tel:”
【发布时间】:2022-06-13 23:32:04
【问题描述】:

第一部分:

所以我想创建一个函数来检测字符串中的电话号码并将其转换为tel: 链接。我有一个检测电话号码的功能:

 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);
}

如果你打电话:

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

它将返回true。但如果我有一个字符串,它会返回false

例子:

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

如何用字符串检测它?

第二部分

一旦在字符串中检测到电话号码,我如何将其包装在 tel: 链接中?

例子:

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>"

我怎样才能让这一切成为可能?

【问题讨论】:

    标签: javascript node.js regex


    【解决方案1】:

    function tel(str) {
      let match = str.match(/^(.*)(\d{3}\-\d{3}\-\d{4})$/);
      if (!match) return "";
    
      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"));

    【讨论】:

      猜你喜欢
      • 2014-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-20
      • 1970-01-01
      • 1970-01-01
      • 2014-08-15
      • 1970-01-01
      相关资源
      最近更新 更多