从字符串中提取图像src [英] Extract image src from a string

查看:86
本文介绍了从字符串中提取图像src的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将所有图片元素匹配为字符串,

I'm trying to match all the images elements as strings,

这是我的正则表达式:

html.match(/<img[^>]+src="http([^">]+)/g);

这有效,但我想提取 src 所有图像。所以当我在这个String上执行正则表达式时:

This works, but I want to extract the src of all the images. So when I execute the regular expression on this String:

< img src =http://static2.ccn.com/ccs/ 2013/02 / img_example.jpg />

它返回:

http://static2.ccn.com/ccs/2013/02/img_example.jpg

推荐答案

您需要使用捕获组()来提取网址,如果您想要全局匹配 g ,即不止一次,使用捕获组时,需要在循环中使用 exec match 全局匹配时忽略捕获组。)

You need to use a capture group () to extract the urls, and if you're wanting to match globally g, i.e. more than once, when using capture groups, you need to use exec in a loop (match ignores capture groups when matching globally).

例如

var m,
    urls = [], 
    str = '<img src="http://site.org/one.jpg />\n <img src="http://site.org/two.jpg />',
    rex = /<img[^>]+src="?([^"\s]+)"?\s*\/>/g;

while ( m = rex.exec( str ) ) {
    urls.push( m[1] );
}

console.log( urls ); 
// [ "http://site.org/one.jpg", "http://site.org/two.jpg" ]

这篇关于从字符串中提取图像src的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆