ZBLOG

浏览器环境,前端解析html字符串的解析库,我需要提取所有的href action src 标签,不依赖DOMParser

在浏览器环境中,如果你需要解析 HTML 字符串并提取 hrefactionsrc 等属性,同时 不依赖 DOMParser,可以使用以下方法:


方案1:正则表达式(适合简单场景)

如果 HTML 字符串结构简单(无嵌套或复杂属性),可以用正则匹配:

function extractAttributes(htmlString) {
    const attributes = ['href', 'action', 'src'];
    const results = {};

    attributes.forEach(attr => {
        const regex = new RegExp(`${attr}=["']([^"']+)["']`, 'gi');
        const matches = htmlString.matchAll(regex);
        results[attr] = Array.from(matches, match => match[1]);
    });

    return results;
}

// 示例用法
const html = `
    <a href="https://example.com">Link</a>
    <form action="/submit"></form>
    <img src="image.png">
`;
console.log(extractAttributes(html));
// 输出: { href: ["https://example.com"], action: ["/submit"], src: ["image.png"] }

缺点

  • 无法处理复杂的 HTML(如属性中包含引号或嵌套标签)。
  • 可能误匹配注释或 JavaScript 代码中的相似字符串。

方案2:动态创建 DOM 元素(无 DOMParser

通过临时创建一个隐藏的 DOM 元素(如 div),将 HTML 字符串插入其中,然后遍历 DOM 节点提取属性:

function extractAttributesWithDOM(htmlString) {
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = htmlString;
    
    const elementsWithAttributes = tempDiv.querySelectorAll('[href], [action], [src]');
    const result = { href: [], action: [], src: [] };

    elementsWithAttributes.forEach(el => {
        if (el.href) result.href.push(el.href);
        if (el.action) result.action.push(el.action);
        if (el.src) result.src.push(el.src);
    });

    return result;
}

// 示例用法
const html = `
    <a href="https://example.com">Link</a>
    <form action="/submit"></form>
    <img src="image.png">
`;
console.log(extractAttributesWithDOM(html));

优点

  • 更可靠,能正确处理复杂 HTML。
  • 无需第三方库。

注意

  • 如果输入的 HTML 包含 <script> 或恶意代码,可能会被执行(需确保来源可信)。

方案3:使用轻量级解析库(推荐)

如果需要更健壮的解析,可以使用专为浏览器设计的轻量级库(不依赖 DOMParser):

  1. htmlparser2
    ”`javascript import { parseDOM } from ‘htmlparser2’;

function parseHTML(html) {

   const dom = parseDOM(html);
   const result = { href: [], action: [], src: [] };

   dom.forEach(node => {
       if (node.type === 'tag' && node.attribs) {
           if (node.attribs.href) result.href.push(node.attribs.href);
           if (node.attribs.action) result.action.push(node.attribs.action);
           if (node.attribs.src) result.src.push(node.attribs.src);
       }
   });

   return result;

}


2. **[linkedom](https://github.com/WebReflection/linkedom)**  
   ```javascript
   import { parseHTML } from 'linkedom';

   const { document } = parseHTML('<html>...your html...</html>');
   // 然后使用标准 DOM API 操作

总结建议

  • 简单需求 → 用正则表达式(注意局限性)。
  • 安全可靠 → 动态创建 DOM + querySelectorAll
  • 复杂场景 → 使用 htmlparser2/linkedom

如果有其他特殊需求,可以进一步优化逻辑!


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=23126

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?