trim.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. var baseToString = require('./_baseToString'),
  2. baseTrim = require('./_baseTrim'),
  3. castSlice = require('./_castSlice'),
  4. charsEndIndex = require('./_charsEndIndex'),
  5. charsStartIndex = require('./_charsStartIndex'),
  6. stringToArray = require('./_stringToArray'),
  7. toString = require('./toString');
  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. module.exports = trim;