JavaScript String Methods

Search, cut, change case, split and clean up text.

Lesson 8 of 56Beginner12 min read

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

MethodExampleResult
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

MethodExampleResult
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

MethodExampleResult
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

MethodExampleResult
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, toLowerCase and toUpperCase tidy and reformat text.
  • includes, startsWith, endsWith and indexOf search text and are case-sensitive.
  • slice cuts out part of a string; split and join convert 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.

Example 1

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!
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 3Remove the spaces, then lowercase, chained together.
  2. Lines 6 to 7Simple checks with includes and endsWith.
  3. Line 8The original string is untouched; methods return new strings.
Example 2

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(" 🍓 "));
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 2Find the position of the last dot.
  2. Line 4Everything before the dot: the name.
  3. Line 5Everything after it: the extension.
  4. Line 8Split a comma-separated string into an array.
  5. Line 10Join the array back with a fun separator.
Example 3

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));
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 2A URL "slug" from a title.
  2. Line 7padStart gives a timer display like 05:07.
  3. Line 10Show only the last four digits of a card number.

Common JavaScript String Methods Mistakes

Expecting the original to change

Don't
let name = "sam";
name.toUpperCase();
console.log(name); // still "sam"
Do
let name = "sam";
name = name.toUpperCase();
console.log(name); // "SAM"

Case-sensitive searching

Don't
"Hello World".includes("world"); // false
Do
"Hello World".toLowerCase().includes("world"); // true

replace only changes the first match

Don't
"1-2-3".replace("-", "+"); // "1+2-3"
Do
"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.

Fill in the blankseasy

Remove the spaces and make it uppercase.

const code = "  abc123  ";
const clean = code.().();
console.log(clean); // "ABC123"
Predict the outputeasy

What does this print?

console.log("butterfly".slice(0, 6));
Predict the outputmedium

What does this print?

const tags = "html, css, js".split(", ");
console.log(tags.length, tags[2]);
Fix the bugmedium

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);
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • Logs "Found: true"
  • No errors

JavaScript String Methods Quiz

3 questions to check what you learned.

  1. What does "Hi".repeat(3) return?

    • "HiHiHi"
    • "Hi3"
    • ["Hi", "Hi", "Hi"]
    • "Hi Hi Hi"
  2. What does "banana".indexOf("z") return?

    • 0
    • null
    • -1
    • false
  3. 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:

  1. Trim spaces and lowercase it
  2. Replace the space between first and last name with a dot
  3. Add the last two digits of year to the end (use slice(-2) on String(year))
  4. Log the result: maya.patel26
const fullName = "  Maya Patel ";
const year = 2026;
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • Logs "maya.patel26"