UNPKG

voca

Version:

The ultimate JavaScript string library

41 lines (35 loc) 1.26 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 { c as clipNumber, M as MAX_SAFE_INTEGER, t as toInteger } from './internal/to_integer.js'; /** * Truncates `subject` to a new `length`. * * @function truncate * @static * @since 1.0.0 * @memberOf Chop * @param {string} [subject=''] The string to truncate. * @param {int} length The length to truncate the string. * @param {string} [end='...'] The string to be added at the end. * @return {string} Returns the truncated string. * @example * v.truncate('Once upon a time', 7); * // => 'Once...' * * v.truncate('Good day, Little Red Riding Hood', 14, ' (...)'); * // => 'Good day (...)' * * v.truncate('Once upon', 10); * // => 'Once upon' */ function truncate(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; } return subjectString.substr(0, length - endString.length) + endString; } export default truncate;