Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Lodash _.truncate() Method

  • Last Updated : 18 Sep, 2020

Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.

The _.truncate() method of String in lodash is used to truncate the stated string if it is longer than the specified string length. The last characters of the string which are truncated are replaced with the stated omission string which is by defaults “…”.

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

Syntax:

_.truncate([string=''], [options={}])

Parameters: This method accepts two parameters as mentioned above and described below:



  • [string=”]: It is the string to be truncated.
  • [options={}]: It is the options object.

Here, the options field are as follows:

  1. [options.length]: It is the maximum string length which is by default 30.
  2. [options.omission=’…’]: It is the string which will indicate that the stated text is omitted.
  3. [options.separator] (RegExp|string): It is the separator pattern which is to be truncated.

Return Value: This method returns the truncated string.

Example 1:

Javascript




// Requiring lodash library
const _ = require('lodash');
  
// Calling _.truncate() method with 
// its parameter
let res = _.truncate(
  'GeeksforGeeks is a computer science portal.');
  
// Displays output
console.log(res);

Output:

GeeksforGeeks is a computer...

Here, the stated string is longer than the maximum length of the string so its truncated and the truncated string to be returned in the output must be of length 30 including the omission string.

Example 2:  

Javascript




// Requiring lodash library
const _ = require('lodash');
  
// Calling _.truncate() method with 
// its parameter
let res = _.truncate(
  'GeeksforGeeks, is a computer science portal.', {
     'length': 22,
     'omission': '***'
   }
);
  
// Displays output
console.log(res);

Output:

GeeksforGeeks, is a***

Here, the maximum length of the string as well as omission string both are specified. So, the resultant output is returned according to that.




My Personal Notes arrow_drop_up
Recommended Articles
Page :