admin管理员组

文章数量:1289509

var rawString = '<a>This is sample</a><img src="example1" /></br><img src="example2" /><p>String ends.</p>'

var output = somefunction(rawString);

output should be:

output = ["example1","example2"];

I didn't find any solution here. I tried using few regex but couldn't work perfactly.

Here are stackoverflow few answers:

Thanks in advance.

var rawString = '<a>This is sample</a><img src="example1." /></br><img src="example2." /><p>String ends.</p>'

var output = somefunction(rawString);

output should be:

output = ["example1.","example2."];

I didn't find any solution here. I tried using few regex but couldn't work perfactly.

Here are stackoverflow few answers:

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

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

Thanks in advance.

Share Improve this question edited May 23, 2017 at 12:25 CommunityBot 11 silver badge asked May 16, 2016 at 6:27 Dee NixDee Nix 1681 silver badge13 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

Using Javascript and regex:

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;
}

Example usage:

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

Returns:

["example1.", "example2."]

Here is your jsfiddle

You can use jQuery(), .filter(), .map(), .get()

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

.Filter work with this example

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

.find Will work with this example

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=\".\" 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);

本文标签: javascriptFind all image src url in string and store in arrayStack Overflow