在字符串中查找所有图像 src URL 并存储在数组中

Find all image src url in string and store in array

本文关键字:URL 存储 数组 src 字符串 查找 图像      更新时间:2023-09-26
var rawString = '<a>This is sample</a><img src="example1.com" /></br><img src="example2.com" /><p>String ends.</p>'
var output = somefunction(rawString);

输出应为:

输出 = ["example1.com","example2.com"];

我在这里找不到任何解决方案。我尝试使用很少的正则表达式,但无法正常工作。

以下是堆栈溢出的几个答案:

https://stackoverflow.com/a/12393724/4203409

https://stackoverflow.com/a/25632187/4203409

提前谢谢。

使用 Javascript 和正则表达式:

function getAttrFromString(str, node, attr) {
    var regex = new RegExp('<' + node + ' .*?' + attr + '="(.*?)"', "gi"), result, res = [];
    while ((result = regex.exec(str))) {
        res.push(result[1]);
    }
    return res;
}

用法示例:

var rawString = '<a>This is sample</a><img src="example1.com" /></br><img src="example2.com" /><p>String ends.</p>';
getAttrFromString(rawString, 'img', 'src');

返回:

["example1.com", "example2.com"]

这是你的杰斯菲德尔

您可以使用

jQuery().filter().map().get()

var output = $(rawString).filter("img").map(function() {return this.src}).get();

.使用此示例的筛选器工作

var rawString = '<a>This is sample</a><img src="example1.com" /></br><img src="example2.com" /><p>String ends.</p>';
var  indices = new Array();
        var result = $(rawString).filter('img').map(function() {
            indices.push(this.src);
        });
        console.log(indices);

.find 将适用于此示例

var rawString = "<style></style><div><div><div class=''><div class=''><div style='position:relative'><div id='' class='sideCross'>X</div> <div class='"vertical-text'">Live Chat</div><img src='"http://localhost/rcm/dashboard'" alt='"text'"/><div class='"speech-bubble'"><img src='".com'" alt='"text'"/></div></div></div></div></div> </div>";
        var  indices = new Array();
        var result = $(rawString).find('img').map(function() {
            indices.push(this.src);
        });
        console.log(indices);