Open In App

Lodash _.truncate() Method

Improve
Improve
Like Article
Like
Save
Share
Report

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 “…”.

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.



Last Updated : 18 Sep, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads