使用正则表达式获取 HTML/Js 中的图片 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4098415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 05:07:06  来源:igfitidea点击:

Use regex to get image URL in HTML/Js

htmlregex

提问by anhtran

I want to get some URLs of images in Js/HTML:

我想在 Js/HTML 中获取一些图像的 URL:

var a = "http://sub.domain.com/uploads/files/11-11-2011/345301-574-1182-393/2202.jpg";
var b = "http://sub.domain.com/uploads/files/23-11-2011/234552-574-2321-232/asd.png";

Looking for solution that will detect image url. So the output will be:

寻找将检测图像 url 的解决方案。所以输出将是:

http://sub.domain.com/uploads/files/11-11-2011/345301-574-1182-393/2202.jpg
http://sub.domain.com/uploads/files/23-11-2011/234552-574-2321-232/asd.png

Thanks!

谢谢!

回答by tinifni

Based off the information you've given, this should work:

根据您提供的信息,这应该有效:

(https?:\/\/.*\.(?:png|jpg))

You can add more extensions by adding |extafter jpg. This will allow for strings with httpsas well.

您可以通过|ext在 之后添加更多扩展名jpg。这也将允许使用字符串https

Note: You may want to use the case insensitivemodifier ito make the capture more inclusive. This would look like:

注意:您可能希望使用不区分大小写的修饰符i来使捕获更具包容性。这看起来像:

/(https?:\/\/.*\.(?:png|jpg))/i

回答by Nathan Lippi

A little late to the party, but in trying to do something similar to the OP, I created the following regex, which seems to handle relative links as well as absolute ones:

聚会有点晚了,但在尝试做类似于 OP 的事情时,我创建了以下正则表达式,它似乎可以处理相对链接以及绝对链接:

/([a-z\-_0-9\/\:\.]*\.(jpg|jpeg|png|gif))/i

回答by thejh

Try this:

尝试这个:

/"(http://[^"]*?\.(jpg|png))"/g

$1 is what you want.

1 美元就是你想要的。

回答by zhang ying

var regex = /(http[s]?://.*.(?:png|jpg|gif|svg|jpeg))/i;

var regex = /(http[s]?://.*.(?:png|jpg|gif|svg|jpeg))/i;

This is the result you want

这是你想要的结果