
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:
<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>
Comments