Santosh Shinde
Santosh Shinde

Reputation: 6063

Remove HTML tag from string in AngularJS

I am getting HTML tags in my response, which I want to remove or parse it.

I got the output like

<sometext>

but I want output only

sometext

In the view, I have used the following code

<div ng-bind-html="description"></div>

And in controller

 $scope.description = '&lt;sometext&gt;';

Upvotes: 1

Views: 15817

Answers (3)

claudius iacob
claudius iacob

Reputation: 104

I am still not sure what are you after, but if you are looking for a the text-only content of your html, this should do it (I'm not sure whether it requires full jQuery or works with jQuery Lite though, I do have jQuery in my project):

/* 'stripHTML': returns the concatenated text nodes of the html string provided */
MyApp.filter ('stripHTML', [function () {
    return function (stringWithHtml) {
        var strippedText =  $('<div/>').html(stringWithHtml).text();
        return strippedText;
    };
}]);

It's a (custom) angular filter, so you know how to use it. If this is not what you wanted, then apologies.

Upvotes: 1

Anishnirmal
Anishnirmal

Reputation: 548

Filters are used to modify the data in AngularJS. We can create our own custom filter to remove the HTML tags from a string.

Look at http://www.codeexpertz.com/blog/angularjs/remove-html-tags-angularjs-using-user-defined-filters-example-and-demo for Demo and Sample Code

Filter Code:

return text ? String(text).replace(/<[^>]+>/gm, '') : '';

Upvotes: 3

Sergei Basharov
Sergei Basharov

Reputation: 53850

I would go with a chained regex replace like this to make sure you don't remove those '/' which are out of '<>' tags:

var a = '<tag>hello</tag>'
var b = a.replace(/\/>/g,'')    // Remove self-closing tags right part that look like "/>" as in "<Tag/>"
         .replace(/<\//g,'')    // Remove "</" as in "</closing>"
         .replace(/[<>]/g,'');  // Remove the rest "<" or ">"
console.log(b) // taghellotag

This code is still not perfect as doesn't look for < and > used outside of tags.

Here is the fiddle:

var a= '<tag>hello</tag>'
var b = a.replace(/\/>/g,'')
         .replace(/<\//g,'')
         .replace(/[<>]/g,'');
console.log(b)

Upvotes: 4

Related Questions