Strings come with dozens of built-in methods, which are small tools you call with a dot, such as name.toUpperCase(). They let you tidy up what visitors type, search through text, cut out pieces and reformat values, often in a single line.
You don't need to memorise every method. Most everyday tasks use about a dozen of them, and this lesson groups those by job so you know where to look. Keep one rule in mind throughout: strings never change in place. Every method returns a new string, so store the result in a variable if you want to keep it.
Changing case and removing spaces
| Method | Example | Result |
|---|---|---|
toUpperCase() | "hi".toUpperCase() | "HI" |
toLowerCase() | "HeLLo".toLowerCase() | "hello" |
trim() | " hi ".trim() | "hi" |
trimStart() / trimEnd() | Removes spaces from one side |
trim() is worth running on almost every value typed into a form. Visitors often add a space at the end of an email address without noticing, and that space can make a perfectly good address fail a check.
Searching inside a string
| Method | Example | Result |
|---|---|---|
includes() | "pancake".includes("cake") | true |
startsWith() | "https://x".startsWith("https") | true |
endsWith() | "photo.jpg".endsWith(".jpg") | true |
indexOf() | "banana".indexOf("n") | 2 (or -1 if not found) |
All of these searches are case-sensitive. For a search box that feels friendly, convert both the text and the search term to lowercase before comparing them.
Cutting and splitting strings
| Method | Example | Result |
|---|---|---|
slice(start, end) | "JavaScript".slice(0, 4) | "Java" (the end position isn't included) |
slice(-n) | "photo.jpg".slice(-3) | "jpg" |
split(separator) | "a,b,c".split(",") | ["a", "b", "c"] |
array.join(sep) | ["a","b"].join(" & ") | "a & b" |
split and join work as a pair. Split a string into an array, change the array, then join it back into a string. You'll use this pattern often once you've learned array methods.
Replacing, padding and repeating
| Method | Example | Result |
|---|---|---|
replace(a, b) | "I like cats".replace("cats", "dogs") | Replaces the first match only |
replaceAll(a, b) | "a-b-c".replaceAll("-", " ") | "a b c" |
padStart(len, char) | "7".padStart(2, "0") | "07" |
repeat(n) | "ha".repeat(3) | "hahaha" |
padStart is perfect for clocks and dates, where 7 should display as "07".
JavaScript String Methods Syntax
Calling a method
const result = text.methodName(arguments);JavaScript String Methods Summary
- String methods are called with a dot and always return a new string.
trim,toLowerCaseandtoUpperCasetidy and reformat text.includes,startsWith,endsWithandindexOfsearch text and are case-sensitive.slicecuts out part of a string;splitandjoinconvert between strings and arrays.- Chain methods together to transform text in one line.
JavaScript String Methods Examples
Each example runs in the page. Edit the code and press Run to see what changes.
Cleaning up user input
const rawEmail = " Alex.Smith@Example.COM ";
const email = rawEmail.trim().toLowerCase();
console.log(email);
console.log(email.includes("@"));
console.log(email.endsWith(".com"));
console.log(rawEmail); // unchanged!Line-by-line explanation
- Line 3Remove the spaces, then lowercase, chained together.
- Lines 6 to 7Simple checks with
includesandendsWith. - Line 8The original string is untouched; methods return new strings.
Cutting with slice and split
const fileName = "holiday-photo.jpeg";
const dot = fileName.lastIndexOf(".");
console.log(fileName.slice(0, dot));
console.log(fileName.slice(dot + 1));
const csv = "Mango,Kiwi,Banana";
const fruits = csv.split(",");
console.log(fruits);
console.log(fruits.join(" 🍓 "));Line-by-line explanation
- Line 2Find the position of the last dot.
- Line 4Everything before the dot: the name.
- Line 5Everything after it: the extension.
- Line 8Split a comma-separated string into an array.
- Line 10Join the array back with a fun separator.
Formatting with replace and padStart
const title = " Learn JavaScript Fast ";
const slug = title.trim().toLowerCase().replaceAll(" ", "-");
console.log(slug);
const minutes = 5;
const seconds = 7;
console.log(`${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`);
const card = "4242424242421234";
console.log("**** " + card.slice(-4));Line-by-line explanation
- Line 2A URL "slug" from a title.
- Line 7
padStartgives a timer display like 05:07. - Line 10Show only the last four digits of a card number.
Common JavaScript String Methods Mistakes
Expecting the original to change
let name = "sam";
name.toUpperCase();
console.log(name); // still "sam"let name = "sam";
name = name.toUpperCase();
console.log(name); // "SAM"Case-sensitive searching
"Hello World".includes("world"); // false"Hello World".toLowerCase().includes("world"); // truereplace only changes the first match
"1-2-3".replace("-", "+"); // "1+2-3""1-2-3".replaceAll("-", "+"); // "1+2+3"JavaScript String Methods in Real Projects
String methods in real apps
Search boxes lowercase and includes to match results, sign-up forms trim emails, blogs turn titles into URL slugs, timers use padStart, and banking apps show "**** " + card.slice(-4). You'll use these daily.
JavaScript String Methods Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Remove the spaces and make it uppercase.
const code = " abc123 ";
const clean = code.().();
console.log(clean); // "ABC123"
trim() removes outer spaces; toUpperCase() capitalises.What does this print?
console.log("butterfly".slice(0, 6));What does this print?
const tags = "html, css, js".split(", ");
console.log(tags.length, tags[2]);The search should find "Pizza" when the user types "pizza", and the result should log Found: true. Fix it.
const menu = "Burger, Pizza, Salad";
const query = "pizza";
const found = menu.include(query);
console.log("Found:", found);- Logs "Found: true"
- No errors
JavaScript String Methods Quiz
3 questions to check what you learned.
What does
"Hi".repeat(3)return?- "HiHiHi"
- "Hi3"
- ["Hi", "Hi", "Hi"]
- "Hi Hi Hi"
What does
"banana".indexOf("z")return?- 0
- null
- -1
- false
What is
"one two three".split(" ")?- ["one", "two", "three"]
- "onetwothree"
- ["o", "n", "e", …]
- 3
JavaScript String Methods Challenge
Username generator
Turn fullName into a username:
- Trim spaces and lowercase it
- Replace the space between first and last name with a dot
- Add the last two digits of
yearto the end (useslice(-2)onString(year)) - Log the result:
maya.patel26
const fullName = " Maya Patel ";
const year = 2026;
- Logs "maya.patel26"