endsWith.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. var baseToString = require('../internal/baseToString');
  2. /* Native method references for those with the same name as other `lodash` methods. */
  3. var nativeMin = Math.min;
  4. /**
  5. * Checks if `string` ends with the given target string.
  6. *
  7. * @static
  8. * @memberOf _
  9. * @category String
  10. * @param {string} [string=''] The string to search.
  11. * @param {string} [target] The string to search for.
  12. * @param {number} [position=string.length] The position to search from.
  13. * @returns {boolean} Returns `true` if `string` ends with `target`, else `false`.
  14. * @example
  15. *
  16. * _.endsWith('abc', 'c');
  17. * // => true
  18. *
  19. * _.endsWith('abc', 'b');
  20. * // => false
  21. *
  22. * _.endsWith('abc', 'b', 2);
  23. * // => true
  24. */
  25. function endsWith(string, target, position) {
  26. string = baseToString(string);
  27. target = (target + '');
  28. var length = string.length;
  29. position = position === undefined
  30. ? length
  31. : nativeMin(position < 0 ? 0 : (+position || 0), length);
  32. position -= target.length;
  33. return position >= 0 && string.indexOf(target, position) == position;
  34. }
  35. module.exports = endsWith;