ItSolutionStuff.com

AngularJS - How to Limit String Length using Filter?

By Hardik Savani • October 20, 2023
Angular

Some case we have enough space to display content, for example you have articale blog and you want to display saveral articale on homepage with limited content 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....

You can do it easily if you are work on any framework or something, but if you want to do on angular then you need to create your own filter for this. you can set limit of characters 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 limit then it will take 50 auto.

{{ randomText | limitChar }}


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

{{ randomText | limitChar:10 }}


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

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

I hope it can help you...

Tags: Angular
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

PHP AngularJS Add Remove Input Fields Dynamically Example

Read Now →

How to Render HTML Value in Ng-repeat in AngularJS?

Read Now →

AngularJS Scroll to a Specific Element using Anchorscroll

Read Now →

AngularJS Convert Comma Separated String to Array Example

Read Now →

AngularJS - How to Create Read More/Less Toggle using Directive?

Read Now →

AngularJS Display Default Image If Original Does Not Exists Example

Read Now →

How to Remove # from URL in AngularJS?

Read Now →

AngularJS Image Upload with Preview Example

Read Now →

How to Hide Div After Some Time in AngularJS?

Read Now →

AngularJS Simple Datepicker Directive Example Tutorial

Read Now →

AngularJS Sorting(using Orderby Filter) Table Data Example

Read Now →

AngularJS - How to Capitalize the First Letter of Word Example

Read Now →

How to Remove HTML Tags from String in AngularJS?

Read Now →