JavaScript中如何将HTML字符串转为DOM对象并提取指定标签内容
JavaScript提取HTML字符串中指定开标签的实现方案
方案1:DOMParser解析(推荐)
这是处理HTML内容最稳妥的方案,不受标签格式、属性顺序、空格换行的影响,兼容性覆盖所有现代浏览器。
var abc = `<div class="hello" data-id="99" data-price="100" data-category="mal"> <div class="hello-category">Hello word</div> <div class="hello-description"><h2>The best burger in town 12345615</h2></div> </div>`; const parser = new DOMParser(); // 把字符串解析为DOM文档 const htmlDoc = parser.parseFromString(abc, 'text/html'); // 选中class为hello的div const targetDiv = htmlDoc.querySelector('.hello'); // 拼接所有属性得到完整开标签 const openTag = `<div ${Array.from(targetDiv.attributes).map(item => `${item.name}="${item.value}"`).join(' ')}>`; console.log(openTag); // 输出结果:<div class="hello" data-id="99" data-price="100" data-category="mal">
方案2:正则匹配(仅适合固定格式场景)
如果你的字符串格式永远固定,可以用正则快速提取,但是不推荐在复杂场景使用,属性包含特殊字符、格式变化都会导致匹配失败。
const openTag = abc.match(/<div\s+class="hello"[^>]+>/i)[0]; console.log(openTag);
内容的提问来源于stack exchange,提问作者Hipólito Huaylla
相关产品推荐
相关产品推荐

