Assuming your string is valid HTML, you could do something like this:
Try it out: http://jsfiddle.net/WsDTL/2/ (updated from original to use .each()
instead of .map()
in order to avoid using .split()
)
var string = "sdsds<div>sdd<a href='http://google.com/image1.gif'>image1</a> sd</div>sdsdsdssssssssssssssssssssssssssssssssssss <p> <a href='some/href'></a> sdsdsdsds </p>sdsds<div>sdd<img src='http://google.com/image1.gif' alt='car for family' /> sd</div>";
var $container = $('<div/>').html(string);
var result = [];
$container.find('a,img').each(function() {
if(this.tagName.toUpperCase() == 'A') {
if($.trim( this.innerHTML ) != '') {
result.push([this.tagName,this.innerHTML,this.href]);
}
} else {
result.push([this.tagName,this.src,this.alt]);
}
});
alert(result);
EDIT:
If you meant that you don't want to process the <a>
if it doesn't have an href
attribute, then change the code to this:
$container.find('a[href],img').each(function() {
if(this.tagName.toUpperCase() == 'A') {
result.push([this.tagName,this.innerHTML,this.href]);
} else {
result.push([this.tagName,this.src,this.alt]);
}
});
EDIT:
For storage as in your comment, you would make results
a javascript object, and store the arrays under the links
and images
keys.
var string = "sdsds<div>sdd<a href='http://google.com/image1.gif'>image1</a> sd</div>sdsdsdssssssssssssssssssssssssssssssssssss <p> <a href='some/href'></a> sdsdsdsds </p>sdsds<div>sdd<img src='http://google.com/image1.gif' alt='car for family' /> sd</div>";
var $container = $('<div/>').html(string);
// store results in a javascript object
var result = {
links:[],
images:[]
};
$container.find('a[href],img').each(function() {
if(this.tagName.toUpperCase() == 'A') {
result.links.push([this.tagName,this.innerHTML,this.href]);
} else {
result.images.push([this.tagName,this.src,this.alt]);
}
});
alert(result.links);
alert(result.images);
You can do 2 separate loops if you prefer. Not sure which will perform better.
http://jsfiddle.net/WsDTL/3/