求一正则:匹配字符串中id为xxx的div

如题:求一正则:匹配字符串中id为xxx的div
<div id="xxx"><span>123</span></div>

阅读 5.1k
5 个回答

JS正则干不了这个事情。
即使用正则不能匹配开闭标签

html结构是后台返回的吗?

const html = `<div id="xxx"><span>123</span></div><div class="yyy" id="yyy"><span>1234</span></div><div id="zzz" class="xxx"><span>12345</span></div><div id=fff><span>123456</span></div>
        `
        var test = html.match(/.*?(id="xxx"|id=xxx)[\s\S].*?(?<=<\/div>)/g);
const html = `
<div id="xxx"><span>123</span></div>
<div class="xxx" id="xxx"><span>1234</span></div>
<div id="xxx" class="xxx"><span>12345</span></div>
<div id=xxx><span>123456</span></div>
`
html.match(/(?<=<div[\s\S]*?(id="xxx"|id=xxx)[^>]*?>)[\s\S]*?(?=<\/div>)/g);   // 不匹配div

html.match(/<div[\s\S]*?(id="xxx"|id=xxx)[^>]*?>([\s\S]*?)<\/div>/g) // 匹配div
const el = document.createElement('div');
el.innerHTML = `your html string`;
document.body.appendChild(el);
const $xxx = document.getElementById('xxx');
const html = $xxx.innerHTML;
// todo

这个单纯用正则式是不可能完成的,因为div可能是嵌套的,最好是dom去匹配。

推荐问题