UNPKG

voca

Version:

The ultimate JavaScript string library

53 lines (46 loc) 1.81 kB
import { i as isNil } from './internal/is_nil.js'; import './is_string.js'; import { c as coerceToString } from './internal/coerce_to_string.js'; import './internal/const.js'; import { R as REGEXP_EXTENDED_ASCII, a as REGEXP_LATIN_WORD, b as REGEXP_WORD } from './internal/const_extended.js'; import { c as clipNumber, M as MAX_SAFE_INTEGER, t as toInteger } from './internal/to_integer.js'; /** * Truncates `subject` to a new `length` and does not break the words. Guarantees that the truncated string is no longer * than `length`. * * @static * @function prune * @since 1.0.0 * @memberOf Chop * @param {string} [subject=''] The string to prune. * @param {int} length The length to prune the string. * @param {string} [end='...'] The string to be added at the end. * @return {string} Returns the pruned string. * @example * v.prune('Once upon a time', 7); * // => 'Once...' * * v.prune('Good day, Little Red Riding Hood', 16, ' (more)'); * // => 'Good day (more)' * * v.prune('Once upon', 10); * // => 'Once upon' */ function prune(subject, length, end) { var subjectString = coerceToString(subject); var lengthInt = isNil(length) ? subjectString.length : clipNumber(toInteger(length), 0, MAX_SAFE_INTEGER); var endString = coerceToString(end, '...'); if (lengthInt >= subjectString.length) { return subjectString; } var pattern = REGEXP_EXTENDED_ASCII.test(subjectString) ? REGEXP_LATIN_WORD : REGEXP_WORD; var truncatedLength = 0; subjectString.replace(pattern, function (word, offset) { var wordInsertLength = offset + word.length; if (wordInsertLength <= lengthInt - endString.length) { truncatedLength = wordInsertLength; } }); return subjectString.substr(0, truncatedLength) + endString; } export default prune;