UNPKG

1.43 kBJavaScriptView Raw
1import baseToString from './_baseToString.js';
2import castSlice from './_castSlice.js';
3import charsEndIndex from './_charsEndIndex.js';
4import charsStartIndex from './_charsStartIndex.js';
5import stringToArray from './_stringToArray.js';
6import toString from './toString.js';
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
49export default trim;