Arrays and Strings: split and join

Grade 7, page 9 of 14. A one-minute read.

Strings and arrays are close cousins, and you can easily turn one into the other.

split(separator) chops a string into an array, cutting wherever it finds the separator:

JavaScript
const sentence = "I love learning JavaScript";
const words = sentence.split(" ");
console.log(words);
console.log(`That sentence has ${words.length} words.`);

const csv = "Paris,Lisbon,Madrid,Brisbane";
console.log(csv.split(","));

console.log("hello".split(""));

It prints

[ 'I', 'love', 'learning', 'JavaScript' ]
That sentence has 4 words.
[ 'Paris', 'Lisbon', 'Madrid', 'Brisbane' ]
[ 'h', 'e', 'l', 'l', 'o' ]

Splitting on an empty string "" breaks a string into individual characters.

join(separator) does the opposite: it glues an array's items together into one string, with the separator in between:

JavaScript
const ingredients = ["rice", "tomatoes", "onions", "pepper"];

console.log(ingredients.join(", "));
console.log(ingredients.join(" + "));
console.log(ingredients.join(""));

It prints

rice, tomatoes, onions, pepper
rice + tomatoes + onions + pepper
ricetomatoesonionspepper

Combine split, reverse (which flips an array's order) and join, and you can do clever things in one line:

JavaScript
const word = "stressed";
const backwards = word.split("").reverse().join("");
console.log(backwards);

const sentence = "the quick brown fox";
console.log(sentence.split(" ").reverse().join(" "));

It prints

desserts
fox brown quick the

Remember reversing a string with a loop in Grade 5? This does the same thing in one line. (Though now you know how it works underneath!)

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning