-1

I have an image tag as below,

var img =  '<img src="http://fmp-8.cit.nih.gov/hembase/search2images/chrX.jpg" alt="image x">';

I want to find the src of this img,i wrote the code as below,

var rex = /<img[^>]+src="?([^"\s]+)"?[^>]*\/>/g;
  while (m = rex.exec(text)) {
    imageUrls.push(m[1]);
 }

But my imageUrls in empty even src element is there. Can any one please help me?

 var m, imageUrls = [],
    rex = /<img[^>]+src="?([^"\s]+)"?[^>]*\/>/g;
  while (m = rex.exec(text)) {
imageUrls.push(m[1]);
    }console.log(imageUrls+'lslsls')
   for (var i = 0; i < imageUrls.length; i++) {
    text = text.replace(/<img[^>]*>/, '<amp-img layout="responsive" class="ampimageheight" src="' + imageUrls[i] + '"    width="200" height= "100"></amp-img>');
  }
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
vak
  • 3
  • 1
  • 6
  • This is another case for [TO͇̹̺ͅƝ̴ȳ̳ TH̘Ë͖́̉ ͠P̯͍̭O̚​N̐Y̡](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – adeneo Sep 11 '17 at 09:37
  • Does this answer your question? [RegEx match open tags except XHTML self-contained tags](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – Brian Tompsett - 汤莱恩 Apr 15 '21 at 18:42

1 Answers1

2

You should parse it as HTML, and work with that. Regex is not suited for parsing HTML

var img =  '<img src="http://fmp-8.cit.nih.gov/hembase/search2images/chrX.jpg" alt="image x">';

var div = document.createElement('div');

div.innerHTML = img;

var src = div.querySelector('img').src;

console.log(src)
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Hi adeneo,I am using node js and updated my code,can you please try for my code with the image tag. – vak Sep 11 '17 at 09:43
  • But the code you posted seems like clientside code? Otherwise you can use something like Cheerio to parse the HTML. You shouldn't be parsing HTML with regular expressions, as it has a high probability of failing. – adeneo Sep 11 '17 at 09:58