UNPKG

awesome-string

Version:

The ultimate JavaScript string library

36 lines (35 loc) 1.27 kB
import clipNumber from 'helper/number/clip_number'; import coerceToString from 'helper/string/coerce_to_string'; import isNil from 'helper/object/is_nil'; import { MAX_SAFE_INTEGER } from 'helper/number/const'; import toInteger from 'helper/number/to_integer'; /** * 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 * as.truncate('Once upon a time', 7); * // => 'Once...' * * as.truncate('Good day, Little Red Riding Hood', 14, ' (...)'); * // => 'Good day (...)' * * as.truncate('Once upon', 10); * // => 'Once upon' */ export default function truncate(subject, length, end) { const subjectString = coerceToString(subject); const lengthInt = isNil(length) ? subjectString.length : clipNumber(toInteger(length), 0, MAX_SAFE_INTEGER); const endString = coerceToString(end, '...'); if (lengthInt >= subjectString.length) { return subjectString; } return subjectString.substr(0, length - endString.length) + endString; }