Remove HTML tags in AngularJS using user defined Filters with example and Demo

Filters are used to modify the data in AngularJS. Here we create a custom filter to remove the HTML tags from a string. “removeHTMLTags” is the filter name. Used regular expression to strip the HTML tags from the given string.

Sample Code:

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

Demo:

Filters to remove HTML tags- AngularJS
Type HTML here..

Un-Trimmed Sting with HTML tags--> {{data.string}}

HTML Filtered text--> {{data.string | removeHTMLTags}}

Example Program:
<html>
 
<head>
  <title>Filters to remove HTML tags- AngularJS</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
 
<body>
  <div ng-app="myApp" ng-controller="myController">
    <div><span>Un-Trimmed Sting with HTML tags--> </span><span>{{data.string}}</span></div>
    <br/>
    <div><span>HTML Filtered text--> </span><span>{{data.string | removeHTMLTags}}</span></div>
  </div>
 
  <script> 
         var myApp = angular.module("myApp", []);
         myApp
         .filter('removeHTMLTags', function () { //removeHTMLTags is the filter name
            return function (text) {
              return text ? String(text).replace(/<[^>]+>/gm, '') : ''; // used regular expression
            };
          })
          .controller('myController', function($scope) {
            $scope.data = {
               string: '<div style="font-weight: bold;">I am a string with HTML tag including style attribute</div>',
            };
         });
      </script>
</body>
 
</html>
Category: 

Comments

mathan (not verified)
Thanks for sharing this useful information