如何用JS函数提取字符串中长度超8位的连续数字并包裹为tel链接?
实现方案
这里有一个简洁可靠的实现方案,刚好能满足你的需求:
核心函数实现
我们可以利用 JavaScript 的正则表达式和字符串替换功能,精准匹配并转换符合要求的数字:
function formatLongPhoneNumbers(str) { // 匹配连续9位及以上的数字(长度大于8位) const longNumberRegex = /(\d{9,})/g; // 将匹配到的数字替换为指定的电话链接标签 return str.replace(longNumberRegex, '<a href="tel:$1" class="button button-positive">$1</a>'); }
针对你的示例场景的完整处理
如果你的输入是包含 <pre><code> 标签的 HTML 字符串,我们可以进一步处理标签转换和内容替换:
function processHtmlWithPhoneNumbers(htmlStr) { // 先处理<code>标签内的内容,替换长数字为电话链接 let processed = htmlStr.replace(/<code>([\s\S]*?)<\/code>/g, (match, codeContent) => { const formattedContent = formatLongPhoneNumbers(codeContent); return `<code>${formattedContent}</code>`; }); // 将<pre>标签替换为<p>标签,匹配你需要的输出格式 processed = processed.replace(/<pre>(.*?)<\/pre>/g, '<p>$1</p>'); return processed; } // 测试你的示例输入 const inputHtml = '<p><strong>html</strong></p> <pre><code>9216143567 is the number and other one is 0112388908 </code></pre>'; const outputHtml = processHtmlWithPhoneNumbers(inputHtml); console.log(outputHtml);
代码说明
- 正则表达式
/(\d{9,})/g:\d匹配任意数字字符{9,}表示匹配至少9次(也就是长度大于8位的连续数字)g标记表示全局匹配,会替换所有符合条件的数字
- 字符串替换逻辑:
- 使用
$1引用正则捕获到的数字内容,动态生成电话链接 - 针对 HTML 标签的处理,我们先用正则提取
<code>内的文本进行替换,再将<pre>替换为<p>以匹配你需要的输出结构
- 使用
- 测试结果:运行上述代码后,会输出你需要的格式:
<p><strong>html</strong></p> <p><code><a href="tel:9216143567" class="button button-positive">9216143567</a> is the number and other one is <a href="tel:0112388908" class="button button-positive">0112388908</a> </code></p>
内容的提问来源于stack exchange,提问作者user2828442
相关产品推荐
相关产品推荐

