简体   繁体   English

如何在js中找到带有alt的图像标签的src

[英]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.

相关问题 如何在javascript execCommand方法中将alt添加到图像src标签? - How to add alt to the image src tag in javascript execCommand methode? 如何使用phantom.js抓取JavaScript注入的图像src和alt? - How to scrape javascript injected image src and alt with phantom.js? 如何根据图片的src选择一个alt? - How to select an alt based on what the src of the image is? 选择所有具有特定src且没有alt标签的图像元素 - Select all image elements with a specific src and no alt tag 如何使用 javascript 获取图像 alt 标签? - How to get the image alt tag with javascript? 如何使用 js 或 jquery 将图像的“src”标签修改为 data-src 以启用延迟加载图像 - How can modify the "src" tag of an image to data-src with js or jquery in order to enable lazy loading images 从<a href>标签中</a>找到src图片值 - Find a src image value from an <a href> tag 如何从alt属性而不是src自动将图像调整为屏幕大小 - how to automatically resize image to screen size from alt attribute and not src 如何为页面上的所有图像使用图像的src填充alt字段 - How to populate alt fields with the src of an image for all images on page 图片标签没有使用 JS 获取 src 属性 - Image tag not getting src attribute using JS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM