String Methods
String methods such as trim, toLowerCase, slice, replaceAll, split, join and padStart tidy and reshape text, and each one hands back a new string while the original stays as it was.
Apprentice · JavaScript · Updated
After this lesson you can
- Tidy and format text with trim, toLowerCase, toUpperCase, slice, replaceAll and padStart
- Split text into an array with split and join an array back into text with join
Key takeaways
- A string never changes in place. A string method hands back a new string, so store it in a variable or use it straight away.
- trim takes spaces off both ends, and toLowerCase and toUpperCase change the capital letters.
- slice takes a piece of a string by position, counted from 0, up to but not including the end position.
- replaceAll swaps every match for something else; replace swaps only the first.
- split cuts text into an array at a separator, join glues an array back into text, and padStart pads a string to a fixed width.
People type the way they type. A sign-up form gets mARIA lopez with spaces in odd places and the caps lock half on, an email in capital letters, a phone number with dashes. Before that text goes on a name badge, a receipt or a search, a program tidies it. That's a job you will do in almost every app that has a form: a store's checkout, a club's member list, a class project's login page. In this lesson you learn the tools for it.
Meet the Riverside 5K Fun Run, a charity race in a city park. Runners sign up online, and the volunteers need clean names for the bibs (the numbered paper squares runners pin on their shirts), a shirt order, and a check-in sheet. Every lesson in this chapter works on its sign-ups, and the names, emails and phone numbers are all made up.
A string never changes: you get a new one
Think of a printed name badge. If it says mARIA, you don't erase letters on it; you print a new badge. JavaScript treats text the same way. A string can't be changed once it exists, so every string method (a function that belongs to a value, called with a dot after it; the . is read "dot") hands you back a new string and leaves the original alone:
const typed = " mARIA ";
const tidy = typed.trim();
console.log(`[${typed}]`);
console.log(`[${tidy}]`);
[ mARIA ]
[mARIA]
The square brackets in the output show where each string starts and ends. typed still has its spaces; the tidied copy is in tidy. Calling typed.trim(); on a line by itself does the work and throws the result away, which is a very common bug. In your textbook this rule is called string immutability: immutable means "can't be changed".
Tidy up: trim, toLowerCase and toUpperCase
You met trim and toUpperCase in Strings and Template Literals. They're the first things to reach for when text comes from a person:
trim()takes spaces (and tabs and line breaks) off both ends, never out of the middle.toLowerCase()makes every letter small, andtoUpperCase()makes every letter a capital.
Emails are the classic case: Maria.Lopez@Example.com and maria.lopez@example.com are the same inbox, so a program compares them in one case:
const emailOnForm = " Maria.Lopez@Example.com ";
const emailOnFile = "maria.lopez@example.com";
const cleaned = emailOnForm.trim().toLowerCase();
console.log(cleaned);
console.log(cleaned === emailOnFile);
maria.lopez@example.com
true
emailOnForm.trim().toLowerCase() is a chain: read it left to right. trim() hands back a new string, and toLowerCase() is called on that new string.
Take a piece: slice
Every character in a string has a position, called its index, counted from 0: in "jamal", j is at index 0 and l at index 4. slice(start, end) hands back the characters from start up to, but not including, end. Leave out end to go to the end of the string, and use a negative number to count from the end:
const word = "jamal";
console.log(word.slice(0, 1));
console.log(word.slice(1));
console.log(word.slice(-3));
const capitalized = word.slice(0, 1).toUpperCase() + word.slice(1).toLowerCase();
console.log(capitalized);
j
amal
mal
Jamal
The last two lines are a recipe you'll use again and again: the first letter as a capital, plus the rest in small letters. It works on "JAMAL" and "jAmAl" too.
Try it. Make a file named slices.js, set const race = "Riverside 5K";, and print race.slice(0, 9), race.slice(10) and race.slice(-2). Before you run it with node slices.js, write down what you expect each line to print.
Swap text: replaceAll
The timing company wants emergency phone numbers written with dashes, like 555-555-0142, and Jamal typed his with dots. replaceAll(find, replaceWith) swaps every match for something else. Its older cousin replace swaps only the first one, which surprises people:
const phone = "555.555.0142";
console.log(phone.replace(".", "-"));
console.log(phone.replaceAll(".", "-"));
const teamName = "Turtle Power Crew";
const teamPageAddress = teamName.toLowerCase().replaceAll(" ", "-");
console.log(teamPageAddress);
555-555.0142
555-555-0142
turtle-power-crew
The last example turns a team name into the kind of text you see in a web address, such as riverside5k.example.com/teams/turtle-power-crew. Two methods, chained, and the job is done.
Pieces and back again: split and join
Sometimes you need the words of a string one at a time. split(separator) cuts a string wherever the separator appears and hands back an array (a numbered list) of the pieces. join(separator) is its partner: it glues an array's items into one string, with the separator between each pair:
const sizes = "S, M, M, XL";
const sizeList = sizes.split(", ");
console.log(sizeList);
console.log(sizeList.length);
const fullName = ["Priya", "Shah"].join(" ");
console.log(fullName);
console.log(["Maria", "Jamal", "Priya"].join(", "));
[ 'S', 'M', 'M', 'XL' ]
4
Priya Shah
Maria, Jamal, Priya
Watch out for messy spaces. Split " mARIA lopez " at every space, and each extra space leaves an empty string "" in the array. The filter method from map and filter keeps only the pieces you want:
const typed = " mARIA lopez ";
console.log(typed.split(" "));
console.log(typed.split(" ").filter((word) => word !== ""));
[ '', '', 'mARIA', '', 'lopez', '' ]
[ 'mARIA', 'lopez' ]
Split, fix each word, join: that's how a program turns mARIA lopez into Maria Lopez. You'll put the whole thing together in Exercise: Fun Run Sign-Ups.
Line things up: padStart
Every bib at the Riverside 5K has a four-digit number: runner 7 wears 0007, runner 58 wears 0058. padStart(length, padding) adds the padding to the front of a string until it's length characters long. Its partner padEnd adds to the end, which lines up columns on a check-in sheet. They're string methods, so turn a number into a string with String() first:
const bib = 7;
console.log(String(bib).padStart(4, "0"));
console.log(String(58).padStart(4, "0"));
console.log(String(12345).padStart(4, "0"));
console.log("Maria Lopez".padEnd(14, ".") + "0007");
console.log("Jamal Reed".padEnd(14, ".") + "0012");
0007
0058
12345
Maria Lopez...0007
Jamal Reed....0012
A string that's already long enough comes back as it is, so 12345 keeps all five digits. Forget the String(), and (7).padStart(4, "0") stops the program with TypeError: 7.padStart is not a function: numbers don't have string methods.
Try it. In a file named bibs.js, print the bib labels for runners 3, 41 and 250, each as Bib 0003 and so on. Then try padStart(6, "*") and see what changes.
Check yourself
2 questions to try on the lesson page.
So what
Text from people is messy, and every form, search box and report you build will clean it. Trim, change the case, slice, swap, split, join and pad, and keep the new string each method hands back.