1 var baseToString = require('../internal/baseToString'),
2 isIterateeCall = require('../internal/isIterateeCall'),
3 isObject = require('../lang/isObject'),
4 isRegExp = require('../lang/isRegExp');
6 /** Used as default options for `_.trunc`. */
7 var DEFAULT_TRUNC_LENGTH = 30,
8 DEFAULT_TRUNC_OMISSION = '...';
10 /** Used to match `RegExp` flags from their coerced string values. */
14 * Truncates `string` if it's longer than the given maximum string length.
15 * The last characters of the truncated string are replaced with the omission
16 * string which defaults to "...".
21 * @param {string} [string=''] The string to truncate.
22 * @param {Object|number} [options] The options object or maximum string length.
23 * @param {number} [options.length=30] The maximum string length.
24 * @param {string} [options.omission='...'] The string to indicate text is omitted.
25 * @param {RegExp|string} [options.separator] The separator pattern to truncate to.
26 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
27 * @returns {string} Returns the truncated string.
30 * _.trunc('hi-diddly-ho there, neighborino');
31 * // => 'hi-diddly-ho there, neighbo...'
33 * _.trunc('hi-diddly-ho there, neighborino', 24);
34 * // => 'hi-diddly-ho there, n...'
36 * _.trunc('hi-diddly-ho there, neighborino', {
40 * // => 'hi-diddly-ho there,...'
42 * _.trunc('hi-diddly-ho there, neighborino', {
46 * // => 'hi-diddly-ho there...'
48 * _.trunc('hi-diddly-ho there, neighborino', {
49 * 'omission': ' [...]'
51 * // => 'hi-diddly-ho there, neig [...]'
53 function trunc(string, options, guard) {
54 if (guard && isIterateeCall(string, options, guard)) {
57 var length = DEFAULT_TRUNC_LENGTH,
58 omission = DEFAULT_TRUNC_OMISSION;
60 if (options != null) {
61 if (isObject(options)) {
62 var separator = 'separator' in options ? options.separator : separator;
63 length = 'length' in options ? (+options.length || 0) : length;
64 omission = 'omission' in options ? baseToString(options.omission) : omission;
66 length = +options || 0;
69 string = baseToString(string);
70 if (length >= string.length) {
73 var end = length - omission.length;
77 var result = string.slice(0, end);
78 if (separator == null) {
79 return result + omission;
81 if (isRegExp(separator)) {
82 if (string.slice(end).search(separator)) {
85 substring = string.slice(0, end);
87 if (!separator.global) {
88 separator = RegExp(separator.source, (reFlags.exec(separator) || '') + 'g');
90 separator.lastIndex = 0;
91 while ((match = separator.exec(substring))) {
94 result = result.slice(0, newEnd == null ? end : newEnd);
96 } else if (string.indexOf(separator, end) != end) {
97 var index = result.lastIndexOf(separator);
99 result = result.slice(0, index);
102 return result + omission;
105 module.exports = trunc;