How to Limit The Length of a String With AngularJS

Here’s another handy AngularJS code snippet which enables the developers to truncate and limit a string to specific number of letters.

var app = angular.module('myApp', []);
app.filter('truncate', function () {
    return function (content, length, tail) {
        if (isNaN(length))
            length = 25;

        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;
        }
    };
});

Usage:

<p>{{ randomText | truncate }}</p>

As you can see, if you don’t specify the length, it will limit string to default 25 letters.

<p>{{ randomText | truncate:10 }}</p>

Above code will limit the text two 10 letter, as we are specifying the limit.

<p>{{ randomText | truncate:10:"...!" }}</p>

In the above, example we are limiting the text to 10 letters also we are specifying the trailing letters.

Read Also: Fix MassAssignmentException in Laravel

0 Comments

Leave a Comment.