Introduction and Overview

Welcome back to our exploration of JavaScript. Today, we're delving into two crucial string methods: split() and join(). Visualize a string as a necklace of beads. split() and join() let you rearrange and recombine these beads. They're essential for text analysis. Our mission today? Learning to apply these tools, even in real-life tasks such as tracking word frequency in a school essay. Let's dive in!

Diving into the split() Method

We should understand two foundational terms: splitting and joining strings — these are often the initial steps in JavaScript text analysis.

Splitting a string breaks a lengthy sentence into smaller chunks, reminiscent of breaking a sentence into words. Meanwhile, joining strings is akin to weaving words into a sentence, merging several strings into one cohesive unit.

First, let's delve into the split() method. This method fractures a string into an array of substrings or "beads". The syntax is clear-cut:

let separator = ...;
let stringArray = originalString.split(separator);

The separator is optional. If omitted, the entire string devolves into one gigantic "bead". Let's illustrate:

let greeting = "Hello World! What a wonderful day out there!";
let words = greeting.split(' '); // Splitting the phrase by whitespaces
console.log(words);
// Outputs: ['Hello', 'World!', 'What', 'a', 'wonderful', 'day', 'out', 'there!']

// Providing No separator returns a list of a single element
console.log(greeting.split());
// Outputs: ["Hello, World! What a wonderful day out there!"]

And what transpires if we employ an empty string as a separator? It will split the phrase into single characters!

let shortGreeting = "Hello, World!"
let characterArray = shortGreeting.split('');
console.log(characterArray);
// Outputs: ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']

As you sense, it's akin to breaking the necklace down into individual beads!

Exploring the join() Method

The join() method is the antithesis of split(). It joins elements of an array into a singular string. The syntax looks like this:

let separator = ...;
let combinedString = stringArray.join(separator);

If no separator is provided, elements unite with a comma (,). Let's revisit our words array:

let words = ['Hello', 'World!', 'What', 'a', 'wonderful', 'day', 'out', 'there!']
let originalString = words.join(' ');
console.log(originalString);
// Outputs: Hello World! What a wonderful day out there!

console.log(words.join());
// Outputs: Hello,World!,What,a,wonderful,day,out,there!

Alternative separators yield varying results:

let list = words.join(', ');
console.log(list);
// Outputs: Hello, World!, What, a, wonderful, day, out, there!
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal