trim.js 1.3 KB

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