Command Palette

Search for a command to run...

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

Cut, search and ask

lastIndexOf finds the last dot, so a name with several dots still splits correctly. substring(4, 0) swapped its arguments; slice(4, 0) returned an empty string.

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?

Cut, search and ask

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Holiday Photos.final
jpg
JPG G undefined
14 -1
true false
true false
true
[Holi] []