I have some bindings in AngularJS and I want to limit the length of characters displayed. It's a quite simple question when you have just a simple text content.
However, I have text that contains HTML tags:
$scope.text = "<span><h1>Example</h1><p>Special Text</p></span>"
and also
$scope.maxNumberOfChar = 10;
When I use the following line it counts the number of chars taking into account HTML tags.
Which could be the best solution to solve this problem and count only the number of chars, discarding HTML tags?
Thanks in advance
I've created a solution, using a simple filter and regex operations.
var appFilters = angular.module('myApp.filters', [])
.filter('limitHtml', function() {
return function(text, limit) {
var changedString = String(text).replace(/<[^>]+>/gm, '');
var length = changedString.length;
return changedString.length > limit ? changedString.substr(0, limit - 1) : changedString;
}
})
and the correspondent usage, similar to limitTo
filter
<span ng-bind-html="text | limitHtml: maxNumberOfChar"></span>
Note that, in this case I am also using an html-binding, specific of my solution.
I created a filter, the logic is not so good, but it works
<span ng-bind-html="text | limitHtml:maxNumberOfChar"></span>
jsfiddle.net/4x6z283a/1/
To count only the number of non HTML chars, use something similar to the answer to this question: angularjs to output plain text instead of html
For example:
var text = "<span><h1>Example</h1><p>Special Text</p></span>";
var length = String(text).replace(/<[^>]+>/gm, '').length;
alert(length);
I've included a further example here: http://jsfiddle.net/n3qjm2u5/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With