Reputation: 524
I'm not very good at filtering and wanted to write a custom filter based on the following:
I call a service that returns a JSON object with HTML String thats concatenated with another string - so the HTML is funky.
I want to get the text1
and text2
form the following returned HTML string:
<span><b>text1</b><b>text2</b>text3</span>
I have no control how the above is returned to me, but i just wanted to get the two values and concatenate them: text1text2
Upvotes: 1
Views: 985
Reputation: 524
Based on DineSH's answer - I did something like this:
$scope.getTextFromHTML = function(html){
var oDOM = new DOMParser().parseFromString(html, "text/xml");
var b = oDOM.documentElement.getElementsByTagName("b");
return b[0].innerHTML+b[1].innerHTML;
};
I have to pre-define the html string since its not on the DOM yet, like so:
var html = "<span><b></b><b></b></span>";
I will probably add a for loop
later in case there is a string I missed, but for now, this is perfect. Thank you for all of your help!
Upvotes: 0
Reputation: 4567
There is a builtin DOM parser - or you can find a parser in your environment. See on MDN parsing XML and Element. So you could do something like this:
var x = "<span><b>text1</b><b>text2</b>text3</span>";
var oDOM = new DOMParser().parseFromString(x, "text/xml");
var b = oDOM.documentElement.getElementsByTagName("b");
b.length // 2
b[1].innerHTML // text2
HTH
Upvotes: 3
Reputation: 134
if you just need to strip the html tags, I think you can use the below code
var noHTML = OriginalString.replace(/(<([^>]+)>)/ig,"");
For a filter implementation
angular.module('myNoHtmlFilterApp', [])
.filter('noHtml', function() {
return function(input) {
input = input || '';
var out = input.replace(/(<([^>]+)>)/ig,"");
return out;
};
})
Upvotes: 1