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

var output = somefunction(rawString);

output should be:

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

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

Here are stackoverflow few answers:

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

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

Thanks in advance.

Community
  • 1
  • 1
Dee Nix
  • 170
  • 1
  • 13

3 Answers3

7

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.com" /></br><img src="example2.com" /><p>String ends.</p>';
getAttrFromString(rawString, 'img', 'src');

Returns:

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

Here is your jsfiddle

Joaquinglezsantos
  • 1,510
  • 16
  • 26
Thamilhan
  • 13,040
  • 5
  • 37
  • 59
5

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

var output = $(rawString).filter("img").map(function() {return this.src}).get();
guest271314
  • 1
  • 15
  • 104
  • 177
  • thanks I tried with given data:
    X
    Live Chat
    text
    NOT WORKING.. :(
    – Dee Nix May 16 '16 at 06:57
  • Your string is not in well formate. Many class are not quoted(' ', " ") and the inner string should be same quoted not both (' ' ," "). You have to use var string ="
    to make your string proper in case of same inner and out quoted. Please correct your string. Pls see my answer below
    – Sunil kumar May 16 '16 at 07:57
0

.Filter work with this example

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 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=\".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);
Sunil kumar
  • 761
  • 5
  • 15