Lodash是一個JavaScript庫,可在underscore.js之上運行。 Lodash幫助處理數組,字符串,對象,數字等。
lodash中String的_.truncate()方法用於截斷所聲明的字符串(如果該字符串長於指定的字符串長度)。被截斷的字符串的最後一個字符將替換為規定的省略字符串,默認情況下為“…”。
用法:
_.truncate([string=''], [options={}])
參數:此方法接受上麵提到和下麵描述的兩個參數:
- [string =”]:它是要截斷的字符串。
- [options = {}]:它是選項對象。
在這裏,選項字段如下:
- [options.length]:它是最大字符串長度,默認為30。
- [options.omission =’…’]:該字符串將指示省略了所說明的文本。
- [options.separator](RegExp | string):分隔符模式將被截斷。
返回值:此方法返回截斷的字符串。
範例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);
輸出:
GeeksforGeeks is a computer...
此處,指定的字符串比字符串的最大長度長,因此其截斷的字符串和要在輸出中返回的截斷的字符串的長度必須為30(包括省略字符串)。
範例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);
輸出:
GeeksforGeeks, is a***
在此,指定字符串的最大長度以及省略字符串。因此,結果輸出將根據此返回。
相關用法
- Node.js fs.truncate()用法及代碼示例
- Node.js fsPromises.truncate()用法及代碼示例
- Node.js fsPromises.truncate()用法及代碼示例
- Node.js filehandle.truncate()用法及代碼示例
- Node.js fs.filehandle.truncate()用法及代碼示例
- Lodash _.method()用法及代碼示例
- Lodash _.sneq()用法及代碼示例
- Lodash _.toQuery()用法及代碼示例
- Lodash _.uniqWith()用法及代碼示例
- Lodash _.xorWith()用法及代碼示例
- Lodash _.head()用法及代碼示例
- Lodash _.remove()用法及代碼示例
- Lodash _.pullAt()用法及代碼示例
- Lodash _.pullAll()用法及代碼示例
- Lodash _.pull()用法及代碼示例
- Lodash _.nth()用法及代碼示例
- Lodash _.takeRight()用法及代碼示例
- Lodash _.take()用法及代碼示例
- Lodash _.sortedLastIndex()用法及代碼示例
- Lodash _.fromPairs()用法及代碼示例
- Lodash _.differenceWith()用法及代碼示例
注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 Lodash _.truncate() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。