简体   繁体   English

如何计算 HTML 字符串中的所有图像标签?

[英]How do I count all the image tags within an HTML string?

I have a string of HTML produced by a WYSIWYG editor.我有一个由所见即所得编辑器生成的 HTML 字符串。 I am using Angular for my project.我正在为我的项目使用 Angular。

Let's say I have some stringified HTML like this:假设我有一些像这样的字符串化 HTML :

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

How can I parse this string on the browser-side and count all the <img> elements?如何在浏览器端解析此字符串并计算所有<img>元素?

Do I need to use regex or is there an NPM package that I can use on the browser-side that will do this for me?我需要使用正则表达式还是有一个 NPM package 我可以在浏览器端使用它来为我做这件事?

Note: I don't want to render this HTML in the browser.注意:我不想在浏览器中渲染这个 HTML。 I just want to count the image tags for validation purposes.我只想计算图像标签以进行验证。

With DOMParser, you can create a document from the string and use querySelectorAll to select and count them:使用 DOMParser,您可以从字符串创建文档并使用querySelectorAll到 select 并计算它们:

 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);

I'd say the fastest and simplest way is to consider that any html element <img> must always start with <img .我想说最快和最简单的方法是考虑任何 html 元素<img>必须始终以<img开头。 You can then just search the number of occurrences.然后,您可以只搜索出现次数。 This also supports malformed html such as <iMg这也支持格式错误的 html 例如<iMg

 var msg = `<p>Here is some text with an image</p><br> <img src="data:base64;{ a base64 string }"/> <iMg src="" />` const n = msg.match(/<img/gim).length console.log(n) // 2

CertainPerformance's answer works, however, you can also use javascript's built-in match function (because it looks like you are looking for a regex-type solution):某些性能的答案有效,但是,您也可以使用 javascript 的内置match function (因为看起来您正在寻找正则表达式类型的解决方案):

 var str = '<p>Here is some text with an image</p><br><img src="data:base64;{ a base64 string }"/>'; numMatches = str.match(/<img/igm); if (numMatches.= null) { numMatches = numMatches;length; } else { numMatches = 0, } //The string "<img" is needed because a text can have the string "img". but angle brackets are specially reserved for HTML tags, Also, this prevents the matching of </img>. in case there is a closing tag (though there typically isn't) console;log(numMatches);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM