简体   繁体   English

如何使用正则表达式获取所有 URL src<Img> JavaScript 中的标签?

[英]How to Regular Expression to get all URL src in <Img> tag in JavaScript?

I have a Regular Expression for handle filter HTML string with JavaScript, i want to get all URL image from src attribute in <img> tag, but i want to support both charecters < > and &lt; &gt;我有一个使用 JavaScript 处理过滤器 HTML 字符串的正则表达式,我想从<img>标签中的src属性获取所有 URL 图像,但我想同时支持< >&lt; &gt; &lt; &gt; . . My sample code like below:我的示例代码如下:

const filterImages = str => {
  const imgRegExp = /\&(?:quot|[gl]t);img.*?src="(.*?)"[^>]+>/g;
  const images = [];
    let img;
    while ((img = imgRegExp.exec(str))) {
      images.push(img[1]);
    }
  return images;
}

I have come up with a bulky regex like this我想出了一个像这样庞大的正则表达式

(?:<img\s+src="(.*?)"[^.]*?\/?>|&lt;img\s+src="(.*?)"[^.]*?\/?&gt;)

I have tested it on a page's html and it seems fine https://regex101.com/r/zifqle/1我已经在页面的 html 上对其进行了测试,看起来不错https://regex101.com/r/zifqle/1

在此处输入图片说明

For convenience you could use named capturing groups, but it seems that they must be unique so the best I can think of is为方便起见,您可以使用命名捕获组,但它们似乎必须是唯一的,所以我能想到的最好的是

(?:<img\s+src="(?<url1>.*?)"[^.]*?\/?>|&lt;img\s+src="(?<url2>.*?)"[^.]*?\/?&gt;)

Also try to include m (multiline) flag with the regex还尝试在正则表达式中包含m (多行)标志

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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