Use regex to get image URL in HTML/Js
I want to get some URLs of ima开发者_运维技巧ges in Js/HTML:
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:
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!
Based off the information you've given, this should work:
(https?:\/\/.*\.(?:png|jpg))
You can add more extensions by adding |ext
after jpg
. This will allow for strings with https
as well.
Note: You may want to use the case insensitive modifier i
to make the capture more inclusive. This would look like:
/(https?:\/\/.*\.(?:png|jpg))/i
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:
/([a-z\-_0-9\/\:\.]*\.(jpg|jpeg|png|gif))/i
Try this:
/"(http://[^"]*?\.(jpg|png))"/g
$1 is what you want.
I created this regex a few days ago:
/^https?:\/\/.*\/.*\.(png|gif|webp|jpeg|jpg)\??.*$/gmi
The ones provided by others in this post work, but will not check for query strings
Example of this regex:
static checkForImage(url){
let regex = /^https?:\/\/.*\/.*\.(png|gif|webp|jpeg|jpg)\??.*$/gmi
let result;
if (url.match(regex)){
result = {
match: url.match(regex)
}
} else {
result = false;
}
return result;
}
checkForImage('https://images-ext-2.discordapp.net/external/yhycJKw8ohsysnU6CBDLQPV4979oQINVmv-fRfu-jL8/%3Fsize%3D2048/https/cdn.discordapp.com/avatars/490535372393021469/a_9e9d0e575eee0221e759257e259681af.gif')
A super strict solution to this would be:
/(http[s]*:\/\/)([a-z\-_0-9\/.]+)\.([a-z.]{2,3})\/([a-z0-9\-_\/._~:?#\[\]@!$&'()*+,;=%]*)([a-z0-9]+\.)(jpg|jpeg|png)/i
var regex = /(http[s]?:\/\/.*\.(?:png|jpg|gif|svg|jpeg))/i;
This is the result you want
精彩评论