Reputation: 3029
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 i.e 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.
Upvotes: 0
Views: 1351
Reputation: 3356
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);
}
Upvotes: 0
Reputation: 48114
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.
Upvotes: 1
Reputation: 7267
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
Upvotes: 0