Reputation: 857
I have a string of HTML produced by a WYSIWYG editor. I am using Angular for my project.
Let's say I have some stringified HTML like this:
'<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?
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?
Note: I don't want to render this HTML in the browser. I just want to count the image tags for validation purposes.
Upvotes: 0
Views: 781
Reputation: 1187
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):
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);
Upvotes: 0
Reputation: 16233
I'd say the fastest and simplest way is to consider that any html element <img>
must always start with <img
. You can then just search the number of occurrences. This also supports malformed html such as <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
Upvotes: 2
Reputation: 370679
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);
Upvotes: 3