Searching, Splitting and Joining

JavaScript ES2024 · ✓ verified by execution on

JavaScript provides powerful methods for finding and replacing text, as well as breaking strings apart into arrays.

Finding with indexOf

The indexOf() method searches for a substring and returns its starting index.

javascript
console.log('CodeLudo'.indexOf('Ludo'));
Output
4

A massive trap for beginners is what happens when the substring is not found:

javascript · visualize
console.log('CodeLudo'.indexOf('Java'));
-1

The -1 Boolean Trap

You might wonder why indexOf() returns -1 instead of something like false or null. Because string indices start at 0, returning 0 would mean the substring was found at the very beginning of the string. The language designers needed a number to represent “not found,” and following older languages like C and Java, they chose -1.

if (text.indexOf('a')) looks like a containment check and is exactly backwards. Every number except 0 is truthy, so a missing letter returns -1 and the block runs. A letter found at position 0 returns 0, which is falsy, so the block is skipped. It fails in both directions at once.

Use includes(). It returns an actual boolean, so there is no index to misread.

indexOf() still earns its place when you need the position rather than the fact — to slice around a separator, say. The rule is to compare it explicitly: indexOf(x) !== -1 says what you mean and cannot be misread by the next person, where a bare if (indexOf(x)) is wrong in two directions at once.

replace() has a related trap. Given a plain string it swaps only the first match, which surprises people expecting every occurrence to change. replaceAll() does what its name says; so does replace() with a regular expression carrying the g flag.

if ("hi".indexOf("z")) Returns -1 -1 is TRUTHY! (Executes) Boolean(-1) if ("hi".includes("z")) Returns false false is FALSY (Skips) Boolean(false)
The indexOf boolean evaluation trap vs includes

Replacing Text

The replace() method searches for a substring and swaps it out with a new string. This is incredibly useful for formatting data or cleaning up templates.

javascript
console.log('hello world'.replace('world', 'there'));
Output
hello there

But what happens if there are multiple matches of the same word?

Predict the output javascript

Read the code. What exactly will it print? Commit to an answer before you look.

let phrase = "apple apple";
let result = phrase.replace("apple", "orange");
console.log(result);
Output
orange apple

(Note: replace() with a string pattern only ever replaces the very first occurrence it finds, leaving the rest of the string entirely untouched! If you want to replace all occurrences, you must use the newer replaceAll() method instead.)

Splitting and Joining

You can convert a string into an array using split(), and reverse the process using join().

javascript
console.log('a,b,c'.split(',').join('-'));
Output
a-b-c

If you use an empty string "" as the separator in split(), it splits the text into individual characters.

javascript
console.log('abc'.split('').join('.'));
Output
a.b.c

Check yourself

What does indexOf() return when the substring is not found?

Reveal answer

-1 — indexOf() always returns -1 if the search string is not found, which evaluates to true in a boolean context!

How many replacements does the replace() method make when given a string pattern?

Reveal answer

Only the first occurrence. — When passing a simple string, replace() only replaces the very first match it finds.

What does split('') with an empty string do?

Reveal answer

Splits the string into individual characters. — Passing an empty string to split() separates every single UTF-16 code unit.

Challenges

Challenge 1 +20 XP

Replace ONLY the first occurrence of 'dog' with 'cat'.

javascript
  • Test 1 — expects "cat dog dog"
Need a hint? (−25% XP)

The replace() method with a string pattern only changes the first match it finds.

Show solution (0 XP)
const text = 'dog dog dog';
const res = text.replace('dog', 'cat');
console.log(res);

Challenge 2 +20 XP

Split the string by spaces and join with dashes.

javascript
  • Test 1 — expects "a-b-c"
Need a hint? (−25% XP)

Use split(' ') to create an array, then chain .join('-') on it.

Show solution (0 XP)
const s = 'a b c';
const res = s.split(' ').join('-');
console.log(res);