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.
Write a function initials(fullName) that returns the capital initials with dots, so initials(" asha rao ") returns "A.R.".
Write maskCard(number) that shows only the last 4 digits of a 16-digit card number string, like "************3456".
Write ensureHttps(url) that adds https:// to the front if the string doesn't already start with http:// or https://.
Explain it without notes
Why must you write s = s.trim() instead of s.trim()?
What is the difference between slice and substring?
How do replace and replaceAll differ, and what is special about $ in the replacement?
Why is includes safer than testing indexOf in an if?
Preview
Console
Nothing logged yet.Expected console output
Holiday Photos.final
jpg
JPG G undefined
14 -1
true false
true false
true
[Holi] []