split.js 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. var baseToString = require('./_baseToString'),
  2. castSlice = require('./_castSlice'),
  3. hasUnicode = require('./_hasUnicode'),
  4. isIterateeCall = require('./_isIterateeCall'),
  5. isRegExp = require('./isRegExp'),
  6. stringToArray = require('./_stringToArray'),
  7. toString = require('./toString');
  8. /** Used as references for the maximum length and index of an array. */
  9. var MAX_ARRAY_LENGTH = 4294967295;
  10. /**
  11. * Splits `string` by `separator`.
  12. *
  13. * **Note:** This method is based on
  14. * [`String#split`](https://mdn.io/String/split).
  15. *
  16. * @static
  17. * @memberOf _
  18. * @since 4.0.0
  19. * @category String
  20. * @param {string} [string=''] The string to split.
  21. * @param {RegExp|string} separator The separator pattern to split by.
  22. * @param {number} [limit] The length to truncate results to.
  23. * @returns {Array} Returns the string segments.
  24. * @example
  25. *
  26. * _.split('a-b-c', '-', 2);
  27. * // => ['a', 'b']
  28. */
  29. function split(string, separator, limit) {
  30. if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {
  31. separator = limit = undefined;
  32. }
  33. limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0;
  34. if (!limit) {
  35. return [];
  36. }
  37. string = toString(string);
  38. if (string && (
  39. typeof separator == 'string' ||
  40. (separator != null && !isRegExp(separator))
  41. )) {
  42. separator = baseToString(separator);
  43. if (!separator && hasUnicode(string)) {
  44. return castSlice(stringToArray(string), 0, limit);
  45. }
  46. }
  47. return string.split(separator, limit);
  48. }
  49. module.exports = split;