startsWith.js 974 B

123456789101112131415161718192021222324252627282930313233343536
  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` starts 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=0] The position to search from.
  13. * @returns {boolean} Returns `true` if `string` starts with `target`, else `false`.
  14. * @example
  15. *
  16. * _.startsWith('abc', 'a');
  17. * // => true
  18. *
  19. * _.startsWith('abc', 'b');
  20. * // => false
  21. *
  22. * _.startsWith('abc', 'b', 1);
  23. * // => true
  24. */
  25. function startsWith(string, target, position) {
  26. string = baseToString(string);
  27. position = position == null
  28. ? 0
  29. : nativeMin(position < 0 ? 0 : (+position || 0), string.length);
  30. return string.lastIndexOf(target, position) == position;
  31. }
  32. module.exports = startsWith;