[英]How to find src of an image tag with alt in js
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,我想找到这个img的src,我写的代码如下,
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.但是我的 imageUrls 在空甚至 src 元素中。 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>');
}
You should parse it as HTML, and work with that.您应该将其解析为 HTML,然后使用它。 Regex is not suited for parsing HTML正则表达式不适合解析 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.