text-shaver
Version:
A customizable module for trimming text using characters/words/sentences limits and adding trailing characters.
106 lines (98 loc) • 2.88 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.default = shaveText;
var modes = ['characters', 'words', 'sentences'];
var defaultOptions = {
mode: modes[0],
preserveWords: false,
limit: 10,
suffix: '(..)'
};
function shaveText(text, options) {
if (text === '') return text;
if (typeof text !== 'string') {
return '';
}
var opts = {};
if (options && (typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object' && Object.prototype.toString.call(options) === '[object Object]') {
for (var key in options) {
var val = options[key];
switch (key) {
case 'mode':
if (modes.indexOf(val) >= 0) {
opts['mode'] = val;
}
break;
case 'preserveWords':
if (typeof val === 'boolean') {
opts['preserveWords'] = val;
}
break;
case 'limit':
if (typeof val === 'number') {
if (val > 0) {
opts['limit'] = val;
}
}
break;
case 'suffix':
if (typeof val === 'string') {
opts['suffix'] = val;
}
break;
default:
}
}
} else {
opts = defaultOptions;
}
for (var _key in defaultOptions) {
if (!opts.hasOwnProperty(_key)) {
opts[_key] = defaultOptions[_key];
}
}
var baseText = '';
var textLength = text.length;
switch (opts.mode) {
case 'characters':
if (!opts.preserveWords) {
baseText = text.substring(0, opts.limit);
} else {
var cText = text.substring(0, opts.limit);
var sIndex = textLength;
while (sIndex >= 0) {
var cChar = cText.charAt(sIndex - 1);
if (cChar === ' ' || cChar === '.') {
baseText = cText.substring(0, sIndex);
break;
}
sIndex--;
}
}
break;
case 'words':
var wordsArr = text.split(' ');
var wordsCount = wordsArr.length;
if (wordsCount > opts.limit) {
wordsArr.length = opts.limit;
}
baseText = wordsArr.join(' ');
break;
case 'sentences':
var sentencesArr = text.split('.');
var sentencesCount = sentencesArr.length;
if (sentencesCount > opts.limit) {
sentencesArr.length = opts.limit;
}
baseText = sentencesArr.join('.');
if (sentencesCount > 1) {
baseText = baseText + '.';
}
break;
default:
}
return baseText.length < textLength ? '' + baseText + opts.suffix : baseText;
}