UNPKG

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