How to Limit String Length using Filter in AngularJS ?

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Today now in this post i would like to share with you How to Limit String Length using Filter in AngularJS ?Some case we don’t have enough space to display full content, for example we have an article blog and if we want to display several article on homepage also with limited content as like this way :

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod

tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,

quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo

consequat. Duis aute irure dolor in reprehenderit in voluptate....

Okay now we can do it this very easily if we are work on any framework or something, but if we want to do on angular then we need to create our own filter for this. we can set to limit of characters by using following filter:

Create Filter:
var app = angular.module('myApp', []);
app.filter('limitChar', function () {
    return function (content, length, tail) {
        if (isNaN(length))
            length = 50;
 
        if (tail === undefined)
            tail = "...";
 
        if (content.length <= length || content.length - tail.length <= length) {
            return content;
        }
        else {
            return String(content).substring(0, length-tail.length) + tail;
        }
    };
});
Use Filter:

If you don’t want to set the limit then it will take 50 auto.

{{ randomText | limitChar }}

Bellow example you can see, we can set the limit specific as we want.

{{ randomText | limitChar:10 }}

Bellow example you can see, we can set the limit specific as well as we can specify last char as we want.

{{ randomText | limitChar:10:"...!!!" }}

Read Also : How to convert Object into Array in PHP?

Thanks for read. I hope it help you. For more you can follow us on facebook.

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →