UNPKG

1.43 kBJavaScriptView Raw
1var baseToString = require('./_baseToString'),
2 castSlice = require('./_castSlice'),
3 charsEndIndex = require('./_charsEndIndex'),
4 charsStartIndex = require('./_charsStartIndex'),
5 stringToArray = require('./_stringToArray'),
6 toString = require('./toString');
7
8/** Used to match leading and trailing whitespace. */
9var reTrim = /^\s+|\s+$/g;
10
11/**
12 * Removes leading and trailing whitespace or specified characters from `string`.
13 *
14 * @static
15 * @memberOf _
16 * @since 3.0.0
17 * @category String
18 * @param {string} [string=''] The string to trim.
19 * @param {string} [chars=whitespace] The characters to trim.
20 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
21 * @returns {string} Returns the trimmed string.
22 * @example
23 *
24 * _.trim(' abc ');
25 * // => 'abc'
26 *
27 * _.trim('-_-abc-_-', '_-');
28 * // => 'abc'
29 *
30 * _.map([' foo ', ' bar '], _.trim);
31 * // => ['foo', 'bar']
32 */
33function trim(string, chars, guard) {
34 string = toString(string);
35 if (string && (guard || chars === undefined)) {
36 return string.replace(reTrim, '');
37 }
38 if (!string || !(chars = baseToString(chars))) {
39 return string;
40 }
41 var strSymbols = stringToArray(string),
42 chrSymbols = stringToArray(chars),
43 start = charsStartIndex(strSymbols, chrSymbols),
44 end = charsEndIndex(strSymbols, chrSymbols) + 1;
45
46 return castSlice(strSymbols, start, end).join('');
47}
48
49module.exports = trim;