我想按如下顺序提取包含width,height属性的所有img标记
<img width="100" height="100" src="somethinng" >
<img height="100" src="somethinng" width="100">
所有可能的情况。。。把它们放在一个阵列里。。。
我还想提取什么img标签,其中只包括高度,不包括宽度。。和宽度相同。。喜欢
<img height="100" src="somethinng" >
这只包括高度,不包括宽度
<img src="somethinng" width="100">
这只包括宽度,不包括高度
我正在使用regex来实现这一点,但不幸的是,这并不起作用。
const regexForHeight = /height="([^"]+)"/gm;
const regexForWidth = /width="([^"]+)"/gmi;
const regexForImgs = /<img[^>]*?>/gmi;
对于任意顺序的宽度和高度匹配,我使用这个
const regexForBoth = /(height="([^"]+)").(width="([^"]+)")|(width="([^"]+)").(height="([^"]+)")/
不要用正则表达式解析HTML
不如试试这个
在NODE中,您将需要一个DOMParser
null
const imgString = `<img width="100" height="100" src="somethinng" >
<img height="100" src="somethinng">`
const domFragment = document.createElement("div");
domFragment.innerHTML = imgString;
const h100 = [];
const w100h100 = [];
[...domFragment.querySelectorAll("img[height='100']")].forEach(img => {
console.log(img.getAttribute("width"))
if (img.getAttribute("width")) w100h100.push(img)
else h100.push(img)
});
console.log(h100)
console.log(w100h100)