如何提取HTML中指定文本?兼容Mobile Safari的Regex方案求助
提取HTML中指定前缀的文本(兼容Mobile Safari)
方案1:无后向断言的正则表达式
既然Mobile Safari不支持后向断言,我们可以换一种思路,直接匹配目标前缀并捕获后续文本:
const htmlStr = "<div><span class=\"label\"> <b>19:43:08 pm</b></span> <strong><span style=\"cursor:pointer;\">Gello:</span></strong> <span><strong>These are my favorite sports -- <div><button class='btn' type='button' style='font-weight:bold;'>BASEBALL</span></button></div> gets <div class='dropdown' style='display:inline-block;'><button class='btn' type='button' data-toggle='dropdown' style='font-weight:bold;'>FOOTBALL</span></button></div> oijd;osijf osidj osd jfsoij fosj f.</strong></span></div>"; // 正则匹配:定位目标前缀后,捕获到下一个标签前的所有文本 const regex = /style='font-weight:bold;'>([^<]+)/g; const results = []; let match; while ((match = regex.exec(htmlStr)) !== null) { // 去除文本首尾空白后存入结果数组 results.push(match[1].trim()); } console.log(results); // 输出 ["BASEBALL", "FOOTBALL"]
正则逻辑说明:
style='font-weight:bold;'精准匹配目标前缀([^<]+)捕获所有<之前的内容(即标签内的纯文本)- 配合
g全局标志,通过循环exec获取所有匹配结果,完全兼容Mobile Safari。
方案2:DOM解析(更鲁棒)
正则处理HTML容易受标签结构变化影响,用DOM解析更可靠,浏览器原生支持:
const htmlStr = "<div><span class=\"label\"> <b>19:43:08 pm</b></span> <strong><span style=\"cursor:pointer;\">Gello:</span></strong> <span><strong>These are my favorite sports -- <div><button class='btn' type='button' style='font-weight:bold;'>BASEBALL</span></button></div> gets <div class='dropdown' style='display:inline-block;'><button class='btn' type='button' data-toggle='dropdown' style='font-weight:bold;'>FOOTBALL</span></button></div> oijd;osijf osidj osd jfsoij fosj f.</strong></span></div>"; // 将HTML字符串解析为DOM文档 const parser = new DOMParser(); const doc = parser.parseFromString(htmlStr, 'text/html'); // 选择所有style包含font-weight:bold的元素 const targetElements = doc.querySelectorAll('[style*="font-weight:bold"]'); // 提取每个目标元素的文本内容 const results = Array.from(targetElements).map(el => el.textContent.trim()); console.log(results); // 输出 ["BASEBALL", "FOOTBALL"]
该方案优势:
- 不受标签属性顺序、格式空格的干扰
- 自动处理HTML结构,避免正则匹配的边缘情况
- 兼容所有现代浏览器(包括Mobile Safari)
内容的提问来源于stack exchange,提问作者KingKongFrog
相关产品推荐
相关产品推荐

