Learn JavaScript · lesson 6 of 60 · about 7 minutes
Reading and Changing Text
Visitors type their names in all sorts of ways. Measure text, pick out letters, and tidy it with slice, trim and toUpperCase.
What you'll learn
- Use .length and indexes
- Cut text with slice()
- Change text with string methods
Messy names
Sam's page asks visitors for their name, and people type all sorts: " aDA ", with stray spaces and odd capitals. Greeting them with *Hello, aDA !* looks broken. To tidy it, you need to read text one letter at a time and change it.
Positions start at 0
Every character in a string has a position, called its index, counting from 0. text[0] is the first letter. .length tells you how many characters there are, and slice(start, end) cuts out a piece, stopping just before end.
length, indexes and slice
const surname = "Lovelace";
console.log(surname.length);
console.log(surname[0], surname[7]);
console.log(surname.slice(0, 4));
console.log(surname.slice(4));Output
8
L e
Love
laceString methods
| Method | Does |
|---|---|
| toUpperCase() | ALL CAPS |
| toLowerCase() | all lowercase |
| trim() | Removes spaces from both ends |
| replace(a, b) | Swaps the first a for b |
| includes(x) | true if x is inside |
A method returns a new string. The text you called it on never changes, so store the result if you want to keep it.
Step through: a method that isn't stored changes nothing
let typed = " aDA ";
typed.trim();
typed = typed.trim();
console.log(typed);Output
aDATidying the name
Now the problem from the start: trim the spaces, then build the name from its first letter in capitals and the rest in lowercase.
Any way they type it, the page greets them properly
const typed = " aDA ";
const clean = typed.trim();
const visitor = clean[0].toUpperCase() + clean.slice(1).toLowerCase();
document.querySelector("#visitor").textContent = `Hello, ${visitor}!`;Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.