Array .join() / String .split()
Methods for converting between arrays and strings. join() converts an array to a string, and split() converts a string to an array.
Syntax
// Joins all elements of an array into a string using a separator. var str = array.join(separator); // Splits a string into an array using a separator. var arr = string.split(separator, limit);
Method List
| Method | Description |
|---|---|
| array.join(separator) | Joins all elements of the array into a single string using the specified separator and returns it. If the separator is omitted, a comma (,) is used. |
| string.split(separator, limit) | Splits the string at each occurrence of the specified separator and returns the result as an array. If a limit is specified, the number of elements in the returned array is capped at that value. |
Sample Code
// Convert an array to a string.
var fruits = ["apple", "orange", "grape"];
console.log(fruits.join(", ")); // Outputs: "apple, orange, grape"
console.log(fruits.join("-")); // Outputs: "apple-orange-grape"
console.log(fruits.join("")); // Outputs: "appleorangegrape" (no separator)
console.log(fruits.join()); // Outputs: "apple,orange,grape" (comma used when omitted)
// Convert a string to an array.
var csv = "Alice,Bob,Charlie";
var names = csv.split(",");
console.log(names); // Outputs: ["Alice", "Bob", "Charlie"]
// Split into individual characters.
var chars = "Hello".split("");
console.log(chars); // Outputs: ["H", "e", "l", "l", "o"]
// Specify a limit.
var parts = "a-b-c-d-e".split("-", 3);
console.log(parts); // Outputs: ["a", "b", "c"] (only the first 3 elements)
// Combine join and split to replace a substring.
var text = "I like apples";
var replaced = text.split("apples").join("oranges");
console.log(replaced); // Outputs: "I like oranges"
Overview
array.join() and string.split() are complementary methods for converting between arrays and strings. They are fundamental string manipulation tools used in a wide variety of situations, such as processing CSV data, building paths, and splitting or joining words.
When array.join() encounters null or undefined elements in the array, it treats them as empty strings. Passing an empty string as the separator concatenates all elements directly with nothing between them. A common technique in HTML generation is to build an array of tag strings and then combine them with join("").
string.split() also accepts a regular expression as its separator. For example, "a1b2c3".split(/[0-9]/) splits on every digit and returns ["a", "b", "c", ""]. Passing an empty string splits the string into individual characters, but note that surrogate pairs (such as emoji) will not be split correctly with this approach.
Browser Compatibility
4.5 or earlier ×
3 or earlier ×
Android Browser
37+ ○
Chrome Android
36+ ○
17 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.