简体   繁体   中英

How to find image tags in a string in node js

I have a string with image tags like below

 var str = '<img src="www.client.jpg><img src="www.custums.png">';

I have to find the image tags and src ie I need to push the image tags into an array but right now I cannot use jsdom since I had a version problem right now in my server.So, can anyone please suggest me help to do this with not using jsdom.Thanks.

Just split the string and then filter to the urls like so;

var str = '<img src="www.client.jpg"><img src="www.custums.png">';

console.log(str.split("\"").filter(t => t.startsWith("www.")));

Your example was missing a ", it would make it so this doesn't parse correctly, but assuming the html is actually of that form but without errors it will give you just the urls.

you can use xpath to extract, the path would be //img@src . alternatively, you can use an xml to json parser ; sth like fast-xml-parser

Split the string into an array of image tag. Convert strings into HTML DOM objects as shown below. Then you can easily get the src of image tag.

 var str = "<img src='www.client.jpg'><img src='www.custums.png'>"; var newstring = str.replace(/></gi, ">,<"); // Replace '><' with '>,<' so that you can split with ',' var imgs = newstring.split(","); for(i=0; i<imgs.length; i++) { // Create a temporary div, assign img string as its innerHTML, then gets its content var d = document.createElement('div'); d.innerHTML = imgs[i]; // Reassign the imgs array with HTML DOM object instead of string imgs[i] = d.firstChild; console.log(imgs[i].src); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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