當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Lodash _.truncate()用法及代碼示例

Lodash是一個JavaScript庫,可在underscore.js之上運行。 Lodash幫助處理數組,字符串,對象,數字等。

lodash中String的_.truncate()方法用於截斷所聲明的字符串(如果該字符串長於指定的字符串長度)。被截斷的字符串的最後一個字符將替換為規定的省略字符串,默認情況下為“…”。

用法:

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

參數:此方法接受上麵提到和下麵描述的兩個參數:

  • [string =”]:它是要截斷的字符串。
  • [options = {}]:它是選項對象。

在這裏,選項字段如下:



  1. [options.length]:它是最大字符串長度,默認為30。
  2. [options.omission =’…’]:該字符串將指示省略了所說明的文本。
  3. [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***

在此,指定字符串的最大長度以及省略字符串。因此,結果輸出將根據此返回。

相關用法


注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 Lodash _.truncate() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。