Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.1 — String Methods
JavaScript · Example 2 of 3 ES2021+

split, join, replace and replaceAll

In replacement text $$ means one $. A replacement function's return value is used exactly as it is, with no $ rules. Splitting an empty string gives an array with one empty string, not an empty array.

Strings come with built-in methods to cut out pieces (slice), search (indexOf, includes, startsWith), split and join, replace text, trim spaces, pad to a width, repeat and read from the end (at). None of them change the original string: each returns a new one.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a function initials(fullName) that returns the capital initials with dots, so initials(" asha rao ") returns "A.R.".

02

Write maskCard(number) that shows only the last 4 digits of a 16-digit card number string, like "************3456".

03

Write ensureHttps(url) that adds https:// to the front if the string doesn't already start with http:// or https://.

Explain it without notes

01

Why must you write s = s.trim() instead of s.trim()?

02

What is the difference between slice and substring?

03

How do replace and replaceAll differ, and what is special about $ in the replacement?

04

Why is includes safer than testing indexOf in an if?

split, join, replace and replaceAll ES2021+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

[ 'red', 'green', 'blue', 'yellow' ]
red | green | blue | yellow
[ 'a', 'b' ]
[ '' ] [ 'h', 'i' ]
one dog, two cats
one dog, two dogs
Cost: $10
Cost: $$10
snake case name