Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract content of html tags from a string using javascript or angularjs?

I have a string containing content in some html tags and also some text alone.

It looks like this :

var str =  "<p></p><p><i>blabla</i></p><p><i><b>blaaaaaablaaaaa</b></i></p><iframe src="..." height="111" width="333"></iframe><p></p><p><sub>hello blabla</sub></p><p><br></p><iframe src="..." height="444" width="888"></iframe>"

I would like to extract somehow in Javascript or AngularJS only some tag (including content and attributes) then put them into an array.

For example, if I want only <iframe> tag, I should have this :

var array = ["<iframe src='...' height='111' width='333'></iframe>", "<iframe src='...' height='444' width='888'></iframe>"];

If I want <p> tag then :

var array = ["", "<i>blabla</i>","<i><b>blaaaaaablaaaaa</b></i>","","<sub>hello blabla</sub>","<br>"];

Any suggestion ? Thanks !

NOTE : Don't give an answer using Jquery please !

like image 885
Emidomenge Avatar asked Nov 28 '25 13:11

Emidomenge


2 Answers

You could create an angular element and get the text out of it.

Example:

$scope.array =[];
$scope.eles=
angular.element(str).find('iframe');
[].forEach.call($scope.eles, function (ctl) {
    $scope.name.push(angular.element(ctl).text())
});

here is a demo: http://jsfiddle.net/Lvc0u55v/5122/


Edit To get all the html of the tag you can do:
angular.element(str).find('iframe');
    [].forEach.call($scope.eles, function (ctl) {
        $scope.name.push(ctl.outerHTML)
    });

demo: http://jsfiddle.net/Lvc0u55v/5123/

like image 96
Naeem Shaikh Avatar answered Nov 30 '25 02:11

Naeem Shaikh


try this code:

var iFrameArr= str.match("<iframe>(.*)<iframe>");
var iFrameContent = iFrameArr[1];
like image 34
Kram Avatar answered Nov 30 '25 03:11

Kram