The split() method in JavaScript is used to divide a string into an array of substrings based on a specified separator. It returns a new array without modifying the original string.
Syntax
string.split(separator, limit)separator: The character, string, or regular expression used to determine where to split the string. If omitted orundefined, the entire string is returned as a single-element array.limit: An optional integer that specifies the maximum number of substrings to include in the array. If provided, the method stops splitting after reaching this limit.
Key Examples
Split by space:
"Hello World".split(" "); // Returns ["Hello", "World"]Split by comma:
"Jan,Feb,Mar".split(","); // Returns ["Jan", "Feb", "Mar"]Split by empty string (UTF-16 code units):
"Hi".split(""); // Returns ["H", "i"]⚠️ Note: Using an empty string as a separator splits by UTF-16 code units, which can break surrogate pairs (e.g., emojis). Use the spread operator
[...str]for correct character splitting.Limit the number of splits:
"a b c d".split(" ", 2); // Returns ["a", "b"]Using regular expressions:
"Hello1World2Test".split(/(\d)/); // Returns ["Hello", "1", "World", "2", "Test"]
Special Cases
If the string is empty and the separator is non-empty, returns
[""].If both string and separator are empty, returns
[].If the separator is a regular expression with capturing groups, the captured groups are included in the result array.
For more details, refer to the MDN Web Docs.
Adding to my Victron system
Split an array into 2 arrays based on conditions
It seems like you're looking for something complicated when something simple will suffice. Why not just:
let foo = names.filter(name => name.length == 4 && /^j/.test(name)); let bar = names.filter(name => name.length == 3 && /^b/.test(name));
If you absolutely must do it in one pass I suppose you can use reduce, but dear god is it ugly:
let result = names.reduce((output, name) => {
if(name.length == 4 && /^j/.test(name)) output[0].push(name);
else if(name.length == 3 && /^b/.test(name)) output[1].push(name);
return output;
}, [[], []]);Are you really telling me that's any easier to read than the first version? Even a simple straightforward for-each loop is easier to read than that mess. I think you should explain more the context of how this will be used.
More on reddit.com