trim.js 1.4 KB

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