trimEnd.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. var baseToString = require('./_baseToString'),
  2. castSlice = require('./_castSlice'),
  3. charsEndIndex = require('./_charsEndIndex'),
  4. stringToArray = require('./_stringToArray'),
  5. toString = require('./toString'),
  6. trimmedEndIndex = require('./_trimmedEndIndex');
  7. /**
  8. * Removes trailing whitespace or specified characters from `string`.
  9. *
  10. * @static
  11. * @memberOf _
  12. * @since 4.0.0
  13. * @category String
  14. * @param {string} [string=''] The string to trim.
  15. * @param {string} [chars=whitespace] The characters to trim.
  16. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  17. * @returns {string} Returns the trimmed string.
  18. * @example
  19. *
  20. * _.trimEnd(' abc ');
  21. * // => ' abc'
  22. *
  23. * _.trimEnd('-_-abc-_-', '_-');
  24. * // => '-_-abc'
  25. */
  26. function trimEnd(string, chars, guard) {
  27. string = toString(string);
  28. if (string && (guard || chars === undefined)) {
  29. return string.slice(0, trimmedEndIndex(string) + 1);
  30. }
  31. if (!string || !(chars = baseToString(chars))) {
  32. return string;
  33. }
  34. var strSymbols = stringToArray(string),
  35. end = charsEndIndex(strSymbols, stringToArray(chars)) + 1;
  36. return castSlice(strSymbols, 0, end).join('');
  37. }
  38. module.exports = trimEnd;