ZBLOG

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

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


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

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

  1. function extractAttributes(htmlString) {
  2. const attributes = ['href', 'action', 'src'];
  3. const results = {};
  4. attributes.forEach(attr => {
  5. const regex = new RegExp(`${attr}=["']([^"']+)["']`, 'gi');
  6. const matches = htmlString.matchAll(regex);
  7. results[attr] = Array.from(matches, match => match[1]);
  8. });
  9. return results;
  10. }
  11. // 示例用法
  12. const html = `
  13. <a href="https://example.com">Link</a>
  14. <form action="/submit"></form>
  15. <img src="image.png">
  16. `;
  17. console.log(extractAttributes(html));
  18. // 输出: { href: ["https://example.com"], action: ["/submit"], src: ["image.png"] }

缺点

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

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

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

  1. function extractAttributesWithDOM(htmlString) {
  2. const tempDiv = document.createElement('div');
  3. tempDiv.innerHTML = htmlString;
  4. const elementsWithAttributes = tempDiv.querySelectorAll('[href], [action], [src]');
  5. const result = { href: [], action: [], src: [] };
  6. elementsWithAttributes.forEach(el => {
  7. if (el.href) result.href.push(el.href);
  8. if (el.action) result.action.push(el.action);
  9. if (el.src) result.src.push(el.src);
  10. });
  11. return result;
  12. }
  13. // 示例用法
  14. const html = `
  15. <a href="https://example.com">Link</a>
  16. <form action="/submit"></form>
  17. <img src="image.png">
  18. `;
  19. console.log(extractAttributesWithDOM(html));

优点

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

注意

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

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

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

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

function parseHTML(html) {

  1. const dom = parseDOM(html);
  2. const result = { href: [], action: [], src: [] };
  3. dom.forEach(node => {
  4. if (node.type === 'tag' && node.attribs) {
  5. if (node.attribs.href) result.href.push(node.attribs.href);
  6. if (node.attribs.action) result.action.push(node.attribs.action);
  7. if (node.attribs.src) result.src.push(node.attribs.src);
  8. }
  9. });
  10. return result;

}

  1. 2. **[linkedom](https://github.com/WebReflection/linkedom)**
  2. ```javascript
  3. import { parseHTML } from 'linkedom';
  4. const { document } = parseHTML('<html>...your html...</html>');
  5. // 然后使用标准 DOM API 操作

总结建议

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

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


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?