Related Articles

Related Articles

How to truncate text in Angular2?
  • Last Updated : 31 Jan, 2020

Approach: It is easy to truncate text in Angular. The truncated text helps us to remove or cut-off portions of text. It abruptly ends the text, reducing the length of the text. It removes text in accordance with the truncate function used.

Syntax:

  • String length is greater than the given characters.
    function(str, length, ending) {........}
  • String truncates to certain words length specified.
    function truncate(str, no_words) {
        return str.split(" ").splice(0, no_words).join(" ");
    }

Example 1: This example shows the way text in Angular is made truncate. Here, the length of the text/string is longer than the given characters. The truncate function is created, which checks the condition if the string length is greater than the given length. It then returns the truncated text accordingly.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html> 
<html
<head
    <title>Truncate text in Angular2</title
  
    <script src
  
    <script src
    </script
</head
      
<body style = "text-align:center;"
          
    <h1 style = "color:green;"
        GeeksForGeeks 
    </h1
          
    <script
text_truncate = function(str, length, ending) {
       
    if (ending == null) {
      ending = '...';
    }
       
    if (str.length > length) {
      return str.substring(0, length - ending.length) + ending;
    } else {
      return str;
    }
  };
   
console.log(text_truncate('Truncate text using Geeks for Geeks',11))
console.log(text_truncate('Truncate text using Geeks for Geeks',11,'!!'))
    </script
</body
</html>                    

chevron_right


Output:

Example 2: This example shows how to truncate the text to certain words. It removes the words that are not included in the given limit. For this purpose: str.split, splice and join are used.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html> 
<html
<head
    <title>Angular JS Route Change</title
  
    <script src
  
    <script src
    </script
</head
      
<body style = "text-align:center;"
          
    <h1 style = "color:green;"
        GeeksForGeeks 
    </h1
          
    <script
function truncate(str, no_words) {
    return str.split(" ").splice(0, no_words).join(" ");
}
  
console.log(truncate('Geeks for Geeks Portal: Truncate Text Using GFG', 6));
    </script
</body
</html>                    

chevron_right


Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :