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:
- [options.length]: It is the maximum string length which is by default 30.
- [options.omission=’…’]: It is the string which will indicate that the stated text is omitted.
- [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( 'neveropen is a computer science portal.' ); // Displays output console.log(res); |
Output:
neveropen 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( 'neveropen, is a computer science portal.' , { 'length' : 22, 'omission' : '***' } ); // Displays output console.log(res); |
Output:
neveropen, 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.