从字符串中提取图像 src

IT技术 javascript regex node.js
2021-03-12 08:15:49

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

这是我的正则表达式:

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

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

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

它返回:

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

6个回答

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

例如

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" ]
结束了这个。否则,它不会拾取所有图像。/<img[^>]+src="([^">]+)/g
2021-04-24 08:15:49
这个 regx 不起作用,因为我们有整个 html 作为字符串,我想从中找出图像 url。你能帮我吗 ?stackoverflow.com/questions/57883657/...
2021-04-26 08:15:49
似乎这个正则表达式不适用于所有 img 标签,但这有效 /<img.*?src="([^">]*\/([^">]*?))".*?>/g;
2021-05-12 08:15:49
有时 img 标签可能在“src”属性之后有高度或其他属性。所以正则表达式应该是 rex = /<img[^>]+src="?([^"\s]+)"?[^>] *\/>/g;
2021-05-16 08:15:49
var myRegex = /<img[^>]+src="(http:\/\/[^">]+)"/g;
var test = '<img src="http://static2.ccn.com/ccs/2013/02/CC_1935770_challenge_accepted_pack_x3_indivisible.jpg" />';
myRegex.exec(test);
谢谢您的回答。它帮助了我。我只想添加这个:var src = myRegex.exec(test); console.log('SRC: ' + src[1]);
2021-04-19 08:15:49
这个 regx 不起作用,因为我们有整个 html 作为字符串,我想从中找出图像 url。你能帮我吗 ?stackoverflow.com/questions/57883657/...
2021-04-29 08:15:49

正如 Mathletics 在评论中提到的那样,还有其他更直接的方法可以从您的标签中检索src属性,<img>例如通过 id、name、class 等检索对 DOM 节点的引用,然后仅使用您的引用来提取您的信息需要。如果您需要对所有<img>元素执行此操作,您可以执行以下操作:

var imageTags = document.getElementsByTagName("img"); // Returns array of <img> DOM nodes
var sources = [];
for (var i in imageTags) {
   var src = imageTags[i].src;
   sources.push(src);
}

但是,如果您有一些限制迫使您使用正则表达式,那么提供的其他答案就可以正常工作。

也许这就是您要寻找的:

我所做的是稍微修改您的正则表达式,然后使用该exec函数来获取匹配字符串的数组。如果您有超过 1 场比赛,则其他比赛将进行results[2]results[3]...

var html = '<img src="http://static2.ccn.com/ccs/2013/02/CC_1935770_challenge_accepted_pack_x3_indivisible.jpg" />';

var re = /<img[^>]+src="http:\/\/([^">]+)/g
var results = re.exec(html);

var source = results[1];
alert(source);

您可以src使用访问该

                                                   |->captured in group 1
                                   ----------------------------------                
var yourRegex=/<img[^>]+src\s*=\s*"(http://static2.ccn.com/ccs[^">]+)/g;
var match = yourRegex.exec(yourString);
alert(match[1]);//src value