Challenge - String operations
Build a text formatting tool with string methods and template literals.
Text formatting challenge
In this challenge you will write a text formatting function. It takes a name string, trims the surrounding spaces and capitalizes the first letter.
The order matters: first clean spaces with trim(), then take the first letter with slice(0, 1) and call toUpperCase(). For the rest of the letters use slice(1) and toLowerCase().
The result is returned with a template literal: `Hello, ${first}${rest}!`. This syntax makes it easy to embed variables inside a string.
Chaining string methods
String methods can be chained. name.trim().slice(0, 1).toUpperCase() calls three methods in a row and each one passes its result to the next.
slice(start, end) returns a substring that includes start and excludes end. slice(1) skips the first letter and gives the rest.
To combine results, a template literal is more readable than the + operator: `Hello, ${first}${rest}!`. Inside ${} you can place any expression.
Exercise Write the formatName function
Define a function named formatName. It should take a name parameter. First clean spaces with trim(). Capitalize the first letter with slice(0, 1).toUpperCase(); lowercase the rest with slice(1).toLowerCase(). Return the result with a `Hello, ${first}${rest}!` template literal.
Show example solution
First call name.trim(). Take the first letter with slice(0, 1).toUpperCase() and the rest with slice(1).toLowerCase(). Combine the result inside a template literal.
Example solution:
function formatName(name) {
const trimmed = name.trim();
const first = trimmed.slice(0, 1).toUpperCase();
const rest = trimmed.slice(1).toLowerCase();
return `Hello, ${first}${rest}!`;
}
Test yourself
-
What does "javascript".slice(0, 4) return?
"javascript".slice(0, 4);- "script"
- "jav"
- "javascript"
- "java"
Show answer
"java" — Correct. slice(0, 4) takes indexes 0, 1, 2 and 3; the result is "java".
-
Embed a variable into a template literal
const greeting = `Hello, ${____}!`;Show answer
const greeting = `Hello, ${name}!`;