split and join
Learn to convert a string to an array with split and back with join.
split to break, join to glue
split breaks a string into pieces at a separator and returns an array. For example "a,b,c".split(",") returns ["a", "b", "c"]. The separator itself is removed.
The reverse, join, glues array elements together with a separator into a single string. ["a", "b", "c"].join("-") returns "a-b-c". Together they let you travel back and forth between strings and arrays.
Empty separator and limit
If you call split with an empty string, every character becomes its own element: "abc".split("") returns ["a", "b", "c"]. It is the shortest way to turn a string into a character array.
You can also pass a second argument as a limit: "a,b,c,d".split(",", 2) returns just ["a", "b"]. The limit caps how many elements the array will hold.
Exercise Split a CSV string into an array
Split the csv string on the comma and store the result in tags. Print it.
Show example solution
const csv = "food,drink,dessert";
// split on the comma
const tags = csv.split(",");
console.log(tags);
Exercise Join the array with a dash
Join the parts array with a dash and store the result in slug. Print it.
Show example solution
const parts = ["javascript", "advanced", "strings"];
// join with a dash
const slug = parts.join("-");
console.log(slug);
Test yourself
-
What does "apple,pear,banana".split(",") return?
"apple,pear,banana".split(",")- 'apple,pear,banana'
- ['apple','pear','banana']
- ['a','p','b']
- ['apple pear banana']
Show answer
['apple','pear','banana'] — Correct. split(",") breaks at every comma and returns a three-element array.
-
Join the array with a dash
const words = ["book", "pencil", "eraser"]; const text = words.____; console.log(text);Show answer
const words = ["book", "pencil", "eraser"]; const text = words.join("-"); console.log(text); -
Match call to behavior
- "a,b".split(",")
- split on comma
- "ab".split("")
- split into chars
- ["a","b"].join("-")
- join with dash
- ["a","b"].join("")
- join with no separator