split.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. var baseToString = require('./_baseToString'),
  2. castSlice = require('./_castSlice'),
  3. isIterateeCall = require('./_isIterateeCall'),
  4. isRegExp = require('./isRegExp'),
  5. reHasComplexSymbol = require('./_reHasComplexSymbol'),
  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. /** Used for built-in method references. */
  11. var stringProto = String.prototype;
  12. /* Built-in method references for those with the same name as other `lodash` methods. */
  13. var nativeSplit = stringProto.split;
  14. /**
  15. * Splits `string` by `separator`.
  16. *
  17. * **Note:** This method is based on
  18. * [`String#split`](https://mdn.io/String/split).
  19. *
  20. * @static
  21. * @memberOf _
  22. * @since 4.0.0
  23. * @category String
  24. * @param {string} [string=''] The string to split.
  25. * @param {RegExp|string} separator The separator pattern to split by.
  26. * @param {number} [limit] The length to truncate results to.
  27. * @returns {Array} Returns the string segments.
  28. * @example
  29. *
  30. * _.split('a-b-c', '-', 2);
  31. * // => ['a', 'b']
  32. */
  33. function split(string, separator, limit) {
  34. if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {
  35. separator = limit = undefined;
  36. }
  37. limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0;
  38. if (!limit) {
  39. return [];
  40. }
  41. string = toString(string);
  42. if (string && (
  43. typeof separator == 'string' ||
  44. (separator != null && !isRegExp(separator))
  45. )) {
  46. separator = baseToString(separator);
  47. if (separator == '' && reHasComplexSymbol.test(string)) {
  48. return castSlice(stringToArray(string), 0, limit);
  49. }
  50. }
  51. return nativeSplit.call(string, separator, limit);
  52. }
  53. module.exports = split;