diff --git a/.gitignore b/.gitignore index 7d6ad5f..f9df951 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .DS_Store node_modules/* +.idea \ No newline at end of file diff --git a/lib/filters/truncate.js b/lib/filters/truncate.js index f26d98e..89becc9 100644 --- a/lib/filters/truncate.js +++ b/lib/filters/truncate.js @@ -10,22 +10,32 @@ var each = require('../utils').each; * * @param {*} input * @param {number} len Number of characters to truncate to. + * @param {boolean} [entireEndingWord=true] Text should end with an entire word * @param {string} [end="..."] Text that will be appended if the string was truncated * @return {*} */ -module.exports = function (input, len, end) { - end = (typeof end === 'undefined') ? '...' : end; +module.exports = function (input, len, entireEndingWord, end) { + entireEndingWord = (typeof entireEndingWord === 'undefined') ? true : entireEndingWord; + end = (typeof end === 'undefined') ? '...' : end; - if (typeof input === 'object') { - each(input, function (value, key) { - input[key] = module.exports(value, len, end); - }); - return input; - } + if (typeof input === 'object') { + each(input, function (value, key) { + input[key] = module.exports(value, len, entireEndingWord, end); + }); + return input; + } + + if (typeof input === 'string' && input.length > len) { + input = input.substring(0, len); - if (typeof input === 'string') { - return input.substring(0, len) + ((input.length > len) ? end : ''); - } + if (entireEndingWord) { + var lastSpace = input.lastIndexOf(' '); + len = lastSpace !== -1 ? lastSpace : len; + input = input.substring(0, len); + } - return input; + return input + ((input.length >= len) ? end : ''); + } + + return input; };