rcpilotp51 rcpilotp51 - 7 months ago 19
Javascript Question

Filter in AngularJS - text in html tags

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

Answer

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