String Methods
Objectives
By the end of this chapter, you should be able to:
- Read a string’s length with
.length - Change case with
.toUpperCase()and.toLowerCase() - Remove surrounding whitespace with
.trim() - Search inside a string with
.includes()and.indexOf() - Extract part of a string with
.slice() - Split a string into an array with
.split() - Replace text with
.replace() - Explain why strings are immutable in JavaScript
💡 Why this matters: Cleaning up user input, checking what a string contains, and pulling pieces out of it are things almost every program does. These eight methods cover the majority of that work.
String Length
Every string has a .length property that tells you how many characters it contains.
const message = "Hello, Priya!";
console.log(message.length);
// 13
Note .length has no parentheses. It’s a property, not a method you call.
Changing Case
.toUpperCase() and .toLowerCase() return a new version of the string in the case you asked for.
const name = "Maya";
console.log(name.toUpperCase());
// MAYA
console.log(name.toLowerCase());
// maya
This is useful for comparisons where case shouldn’t matter, like checking if a user typed “yes” or “YES” the same way.
Trimming Whitespace
.trim() removes whitespace from the start and end of a string. It’s the standard fix for text a user typed with stray spaces.
const input = " sam ";
console.log(input.trim());
// sam
console.log(input.trim().length);
// 3
.trim() only removes whitespace from the edges. Spaces in the middle of the string are left alone.
Searching Inside a String
.includes() answers a yes-or-no question: does this string contain that piece of text?
const email = "erin@example.com";
console.log(email.includes("@"));
// true
.indexOf() answers a related but different question: at what position does that text start? It returns -1 if the text isn’t found.
const email = "erin@example.com";
console.log(email.indexOf("@"));
// 4
Positions are counted from 0. In "erin@example.com", the characters e-r-i-n occupy positions 0 through 3, so @ sits at position 4.
Extracting Part of a String with .slice()
.slice(start, end) returns the part of the string from start up to, but not including, end. If you leave off end, it slices to the end of the string.
const word = "JavaScript";
console.log(word.slice(0, 4));
// Java
console.log(word.slice(4));
// Script
A negative number counts from the end of the string instead of the start.
const word = "JavaScript";
console.log(word.slice(-6));
// Script
"JavaScript" has 10 characters, so -6 means “start 6 characters from the end,” which lands on the same spot as slice(4).
Splitting a String into an Array
.split(separator) breaks a string into an array of pieces, cutting at every occurrence of separator.
const csv = "Erin,Jordan,Maya,Priya";
const names = csv.split(",");
console.log(names);
// [ 'Erin', 'Jordan', 'Maya', 'Priya' ]
This is the standard way to turn one big string, like a line from a CSV file, into an array you can loop over.
Replacing Text with .replace()
.replace(target, replacement) returns a new string with the first match of target swapped out for replacement.
const greeting = "Hello, Sam!";
console.log(greeting.replace("Sam", "Priya"));
// Hello, Priya!
When target is a plain string like this, .replace() only replaces the first match. Later in this module you’ll see how to replace every match using a regular expression.
Strings Are Immutable
Every method you’ve just seen returns a new string. None of them change the original string in place. Strings in JavaScript are immutable: once created, a string’s contents can never be changed.
You can prove this yourself. Call a method on a variable, then log the original variable again:
const original = "sam";
const shouted = original.toUpperCase();
console.log(shouted);
// SAM
console.log(original);
// sam
original is still "sam". .toUpperCase() built a brand new string and handed it back; it never touched original. This is why you almost always see string methods used together with an assignment, like const shouted = original.toUpperCase();. If you just call original.toUpperCase(); and throw away the result, nothing in your program changes.
Try It
- Given
const title = " the great gatsby ";, log its trimmed length. - Given
const city = "Nairobi";, log it in all uppercase and all lowercase. - Given
const url = "https://example.com/profile";, use.includes()to check whether it contains"profile". - Given
const phrase = "learning to code";, use.slice()to extract just"code". - Given
const line = "Sam;Erin;Jordan";, split it into an array using";"as the separator. - Given
const original = "hello";, call.toUpperCase()on it, store the result in a new variable, then log both variables to confirmoriginalis unchanged.
Recap
.lengthgives you the number of characters in a string..toUpperCase()and.toLowerCase()return the string in a different case..trim()removes whitespace from the start and end of a string..includes()checks whether a string contains a piece of text;.indexOf()finds where it starts..slice(start, end)extracts part of a string; negative numbers count from the end..split(separator)turns a string into an array..replace(target, replacement)swaps out the first match oftarget.- Strings are immutable: every method returns a new string instead of changing the original.
Next lesson: building strings with template literals, a cleaner alternative to gluing strings together with +.