endsWith.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. var baseClamp = require('./_baseClamp'),
  2. baseToString = require('./_baseToString'),
  3. toInteger = require('./toInteger'),
  4. toString = require('./toString');
  5. /**
  6. * Checks if `string` ends with the given target string.
  7. *
  8. * @static
  9. * @memberOf _
  10. * @since 3.0.0
  11. * @category String
  12. * @param {string} [string=''] The string to inspect.
  13. * @param {string} [target] The string to search for.
  14. * @param {number} [position=string.length] The position to search up to.
  15. * @returns {boolean} Returns `true` if `string` ends with `target`,
  16. * else `false`.
  17. * @example
  18. *
  19. * _.endsWith('abc', 'c');
  20. * // => true
  21. *
  22. * _.endsWith('abc', 'b');
  23. * // => false
  24. *
  25. * _.endsWith('abc', 'b', 2);
  26. * // => true
  27. */
  28. function endsWith(string, target, position) {
  29. string = toString(string);
  30. target = baseToString(target);
  31. var length = string.length;
  32. position = position === undefined
  33. ? length
  34. : baseClamp(toInteger(position), 0, length);
  35. var end = position;
  36. position -= target.length;
  37. return position >= 0 && string.slice(position, end) == target;
  38. }
  39. module.exports = endsWith;