首页 > 解决方案 > 如何计算 HTML 字符串中的所有图像标签?

问题描述

我有一个由所见即所得编辑器生成的 HTML 字符串。我正在为我的项目使用 Angular。

假设我有一些这样的字符串化 HTML:

'<p>Here is some text with an image</p><br><img src="data:base64;{ a base64 string }"/>'

如何在浏览器端解析这个字符串并计算所有<img>元素?

我是否需要使用正则表达式,或者是否有可以在浏览器端使用的 NPM 包来为我执行此操作?

注意:我不想在浏览器中呈现这个 HTML。我只想计算图像标签以进行验证。

标签: javascripthtmlangular

解决方案


With DOMParser, you can create a document from the string and use querySelectorAll to select and count them:

const str = '<p>Here is some text with an image</p><br><img src="data:base64;{ a base64 string }"/>';
const doc = new DOMParser().parseFromString(str, 'text/html');
const imgs = doc.querySelectorAll('img');
console.log(imgs.length);


推荐阅读