truncate

truncate([length = 30[, suffix = '...']]) -> string

将字符串截短为指定的长度(注意:这里的长度包含了后缀部分), 并添加一个后缀(表示它仅只是一个摘要)。

当然,如果字符串的长度小于或等于指定的长度,String#truncate 将不会对字符串做任何修改。

如果未指定参数,长度默认为 30,并且后缀为 "..."

注意,如果追加了后缀,String#truncate 将后缀也计算在结果值的长度中, 以严格地限制字符串的最终长度等于指定的长度。

样例

'A random sentence whose length exceeds 30 characters.'.truncate();
// -> 'A random sentence whose len...'
'Some random text'.truncate(); 
// -> 'Some random text.' 
'Some random text'.truncate(10); 
// -> 'Some ra...' 
'Some random text'.truncate(10, ' [...]'); 
// -> 'Some [...]' 

'String'.truncate(6);
// -> 'String'