Skip to content
Permalink
Newer
Older
100644 28 lines (28 sloc) 1.1 KB
1
'use strict'
Mar 24, 2015
2
/**
3
* There are cases where important information is at the end of the string and truncating the end isn't helpful.
4
* This function solves that.
5
*
6
* @param {string} str String to be truncated
7
* @param {number} frontLen Number of characters to be remained in front.
8
* @param {number} backLen Number of characters to be remained at the back.
9
* @param {string} truncateStr String that is replaced the truncated portion
10
* @return {string} Truncated string. Defaults to '…' if unspecified.
11
*/
12
module.exports = function (str, frontLen, backLen, truncateStr) {
13
if (str === null) {
14
return ''
15
}
16
var strLen = str.length
17
// Setting default values
18
frontLen = ~~frontLen // will cast to integer
19
backLen = ~~backLen
20
truncateStr = truncateStr || '…'
21
if (frontLen === 0 && backLen === 0 || frontLen >= strLen || backLen >= strLen || (frontLen + backLen) >= strLen) {
22
return str
23
} else if (backLen === 0) {
24
return str.slice(0, frontLen) + truncateStr
25
} else {
26
return str.slice(0, frontLen) + truncateStr + str.slice(strLen - backLen)
27
}
28
}