You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中批量提取字符串内的邮箱、电话及URL?

JavaScript 提取字符串中的邮箱、电话和URL方案

看你的问题,原来用substr加indexOf的方式确实容易踩坑——因为indexOf只会返回第一个匹配项的位置,循环里也没更新查找的起始点,根本没法遍历到600组重复的数据。这里给你推荐用正则表达式来解决,这是处理这类重复模式提取最靠谱的方式。

问题分析

你的数据是重复的Email:xxx Url: yyy Tel: zzz结构,正则可以精准匹配每一组里的目标内容,而且能一次性提取所有结果。

实现方案

1. 分别提取邮箱、URL、电话

这种方式可以单独拿到每一类数据的数组:

// 替换成你的600组数据字符串
const inputStr = "Email:info@abc.com Url: www.example.com Tel: +123-456-789 Email:info@abc.com Url: www.example.com Tel: +123-456-789 ...";

// 提取所有邮箱
const emails = [];
const emailRegex = /Email:([\w.-]+@[\w.-]+\.\w+)/g;
let match;
while ((match = emailRegex.exec(inputStr)) !== null) {
  emails.push(match[1]);
}

// 提取所有URL(自动补全https协议,可选)
const urls = [];
const urlRegex = /Url:\s*((https?:\/\/)?\w+\.\w+(\.\w+)?(\/\S*)?)/g;
while ((match = urlRegex.exec(inputStr)) !== null) {
  const fullUrl = match[1].startsWith('http') ? match[1] : `https://${match[1]}`;
  urls.push(fullUrl);
}

// 提取所有电话
const phones = [];
const phoneRegex = /Tel:\s*(\+?\d+(-\d+)+)/g;
while ((match = phoneRegex.exec(inputStr)) !== null) {
  phones.push(match[1]);
}

// 输出结果
console.log('提取的邮箱列表:', emails);
console.log('提取的URL列表:', urls);
console.log('提取的电话列表:', phones);

2. 一次性提取分组数据(推荐)

如果需要把每组的邮箱、URL、电话对应起来,用一个正则匹配整组,直接拿到结构化的对象数组:

const inputStr = "你的600组数据字符串";
const groupRegex = /Email:([\w.-]+@[\w.-]+\.\w+)\s*Url:\s*((https?:\/\/)?\w+\.\w+(\.\w+)?(\/\S*)?)\s*Tel:\s*(\+?\d+(-\d+)+)/g;
const groupedResults = [];

while ((match = groupRegex.exec(inputStr)) !== null) {
  groupedResults.push({
    email: match[1],
    url: match[2].startsWith('http') ? match[2] : `https://${match[2]}`,
    phone: match[6]
  });
}

// 每组数据都对应一个对象,方便后续处理
console.log('所有分组数据:', groupedResults);

为什么你的原代码失效?

你的代码里:

  • 第一次提取ol是第一个Email:到Url:之间的内容,但循环里再次用myS.indexOf(ol)还是找到第一个匹配的位置,永远拿不到后面的组
  • 没有更新每次查找的起始位置,导致循环600次都是同一个结果

正则的exec方法会自动维护一个lastIndex属性,每次匹配后会从下一个位置开始查找,完美解决了重复提取的问题。

内容的提问来源于stack exchange,提问作者Agent K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 17:48:02