Convert a String to an Array with split() in JavaScript
This Snippet is coded by a user inOnline javascript Compiler. You can see and run this code too.
زبان: JavaScript
The split() method is a built-in JavaScript string method that converts a string into an array. You call it on a string and pass a separator as the first argument. The separator can be a string, such as ',' or ' ', or a regular expression. JavaScript scans the original string, divides it at each match, and returns a new array containing the resulting substrings. The original string remains unchanged.
Inputs: separator is optional. If omitted, the entire string becomes a single array element. limit is also optional; when provided as a non-negative integer, it caps the number of returned elements. Output: a new array. For example, 'a,b,c'.split(',') returns ['a', 'b', 'c'], while 'a,b,c'.split(',', 2) returns ['a', 'b']. An empty string separator, split(''), returns individual UTF-16 code units. A separator that is not found returns an array containing the original string. Consecutive or trailing separators can produce empty strings, and regex capturing groups may be included in the result.
Time complexity is generally O(n), where n is the string length, because the method must scan the input. Space complexity is O(n) for the new array. Use split() when you need simple parsing, tokenization, or character arrays.