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

如何从HTML片段中提取所有匹配font-family的属性值?

提取HTML中font-family引号内字体名称的解决方法

正则表达式修正方案

你之前的正则问题出在贪婪匹配和缺少全局匹配标志:默认的.*会匹配从第一个双引号到最后一个";的所有内容,导致捕获多余字符,且match方法默认只返回第一个匹配结果。

修正后的正则采用非贪婪匹配(.*?)加上全局匹配标志g,同时兼容属性前后的空格:

const targetText = '<span style="font-family:"Comic Sans MS"; color:red;"><span style="font-family:"Boucherie Block"; font-size:16px;">...</span></span>';
const fontRegex = /font-family\s*:\s*"(.*?)";/g;
const fonts = [];
let matchResult;

// 循环捕获所有匹配项
while ((matchResult = fontRegex.exec(targetText)) !== null) {
  fonts.push(matchResult[1]);
}

console.log(fonts); // 输出 ["Comic Sans MS", "Boucherie Block"]

非正则的DOM解析方案

如果HTML结构复杂(比如嵌套标签、style属性顺序多变),用DOM解析更可靠,避免正则的边界情况问题:

const htmlSnippet = '<span style="font-family:"Comic Sans MS"; color:red;"><span style="font-family:"Boucherie Block"; font-size:16px;">...</span></span>';
const parser = new DOMParser();
const doc = parser.parseFromString(htmlSnippet, 'text/html');
const fonts = [];

// 筛选所有包含font-family样式的元素
doc.querySelectorAll('[style*="font-family"]').forEach(el => {
  // 直接读取计算后的font-family属性
  let fontFamily = el.style.fontFamily;
  // 去除首尾可能存在的引号
  fontFamily = fontFamily.replace(/^["']|["']$/g, '');
  fonts.push(fontFamily);
});

console.log(fonts); // 输出 ["Comic Sans MS", "Boucherie Block"]

这种方法的优势是自动处理HTML语法细节,比如style属性内的空格、属性顺序变化,甚至能正确解析font-family:"A", "B"这类多字体声明(若需要拆分多个字体,可再配合简单正则处理)。

内容的提问来源于stack exchange,提问作者Denys Wessels

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 14:58:15