cf.completefrontendCode editorOpen lab
THE JAVASCRIPT FIELD GUIDE

String methods

Search, extract, format, and clean text with JavaScript string methods while remembering that every method returns a new value.

By the end you can
  • 01
    Pick the right familyChoose reading, searching, formatting, replacing, or splitting methods for a text task.
  • 02
    Predict tricky resultsExplain slice versus substring, case-sensitive searches, and first-match replacement.
  • 03
    Build practical helpersClean input, zero-pad IDs, make slugs, and mask account numbers.

A toolbox for text

INTERACTIVE

A string is text. A string method is a tool you call with a dot, such as name.trim() or file.endsWith(".png"). Some methods answer a question. Some pull out a piece. Some return a cleaned-up, reformatted, or replaced copy.

The most important rule is the one from the Strings lesson: strings are immutable. Methods do not edit the original string. They return a new value, so you store the result when you want to keep it.

Real-life analogyString methods are a photocopier with filters

Imagine feeding a sign into a photocopier that has buttons for “trim the edges,” “make this uppercase,” and “replace every comma.” The machine prints a new sign. It does not erase the original.

In real life: Original paper
In JavaScript: The original string
In real life: Copy with the edges trimmed
In JavaScript: text.trim()
In real life: Copy with bigger letters
In JavaScript: text.toUpperCase()
In real life: The original stays in the tray
In JavaScript: String methods return new values

Where the analogy stops: A photocopier makes paper copies, but JavaScript returns values in memory. If you do not store the returned value, the copy is simply not used.

String workbench
A method returns a new stringPop out in the code editor (opens in a new tab)JavaScript
const original = "  Hello, World!  ";const result = original.trim().toLowerCase();console.log(result);console.log(original);
Real resulttrim()
original"··Hello,·World!··"
argumentsnone
result"Hello,·World!"
Try it yourself

The method returns "Hello,·World!". The original is still "··Hello,·World!··" because string methods make a new value.

Spaces are shown as · so trimming, padding, and splitting are easier to see. Reset restores the default string and method.

Try trim(), slice(), includes(), padStart(), replaceAll(), and split(). Notice that the original value stays visible beside the result.

Read and extract pieces

STEP THROUGH

Strings use zero-based indexes, just like arrays. at(index), charAt(index), and charCodeAt(index) all look at one position, but they return different kinds of answers.

  • "JavaScript".at(0) returns "J". at(-1) returns the last character, "t".
  • charAt(0) also returns "J", but charAt(-1) returns an empty string.
  • charCodeAt(0) returns 74, the UTF-16 code unit for J. That number matters more in the Unicode & string internals lesson.
Real-life analogyslice cuts a strip out of a paper banner

Picture the word JavaScript printed on a banner. slice cuts out a strip from a start mark up to, but not including, an end mark.

In real life: Marks between letters
In JavaScript: Indexes in the string
In real life: Cut from mark 0 to mark 4
In JavaScript: text.slice(0, 4)
In real life: Count backward from the right edge
In JavaScript: text.slice(-6)
In real life: No forward strip to cut
In JavaScript: text.slice(4, 0) returns ""

Where the analogy stops: Real scissors can cut either direction. JavaScript methods follow exact rules: slice never swaps its start and end, while substring does.

slice and substring look similar until you use negative or swapped arguments. Step through both cases and compare the printed values.

Compare slice and substring
Step 0 of 5Ready
Your turn: follow the blue line

Predict the two printed lines, then step through how slice and substring treat the same arguments.

Running in
  1. script
Next: line 1
Click the blue line to take the next stepPop out in the code editor (opens in a new tab)JavaScript
const piece = text.slice(-6);const other = text.substring(-6);console.log(piece);console.log(other);
CallStoreChangeResultRun = next line. Ran = already executed.
Recent returnsNothing yet. Start with the blue line.
Choose the arguments

Changing the arguments starts the trace over with the same source shape.

A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

Search and check text

STEP THROUGH

Search methods answer “where is it?” or “is it there?” indexOf returns the first index or -1. lastIndexOf searches from the end. includes returns true or false.

All plain string searches are case-sensitive. "Hello".includes("hello") is false. When users type freely, compare normalized copies: text.toLowerCase().includes(query.toLowerCase()).

startsWith and endsWith are specialized checks. "invoice.pdf".endsWith(".pdf") is clearer than manually slicing the last four characters. Their optional position arguments let you check a smaller window of the string.

Search or replace?
Step 0 of 5Ready
Your turn: follow the blue line

Choose a mode, predict the output, then step through the real string method calls.

Running in
  1. script
Next: line 1
Click the blue line to take the next stepPop out in the code editor (opens in a new tab)JavaScript
const first = text.indexOf("Hello", 1);const hasLower = text.includes("hello");const fixed = text.toLowerCase().includes("hello");console.log(first, hasLower, fixed);
CallStoreChangeResultRun = next line. Ran = already executed.
Recent returnsNothing yet. Start with the blue line.
Choose the family to replay

The displayed code changes with the setting. Predict the console output first.

const text = "Hello hello Hello"; const first = text.indexOf("Hello", 1); const hasLower = text.includes("hello"); const fixed = text.toLowerCase().includes("hello"); console.log(first, hasLower, fixed);
A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

Change the copy, not the original

toUpperCase() and toLowerCase() return case-changed copies. That is useful for display labels and for normalizing comparisons, but remember that human language rules can be surprising.

Case can change length

JavaScript follows Unicode case rules: "ß".toUpperCase() returns SS. Locale-aware methods can vary by language; in an environment with Turkish locale data, "i".toLocaleUpperCase("tr-TR") returns İ.

Use the locale methods when you are formatting human language for people. For IDs, slugs, file extensions, and comparisons you control, plain toLowerCase() is usually easier to reason about.

Format and clean text

EXAMPLES

padStart, padEnd, and repeat create predictable lengths. "7".padStart(3, "0") returns "007"; "1234".padStart(8, "*") returns "****1234"; "ab".repeat(3) returns "ababab".

trim, trimStart, and trimEnd shave whitespace from the edges. Whitespace includes spaces, tabs, newlines, and non-breaking spaces. In real JavaScript, trimming "\t\n  hi  \n" leaves "hi".

Replace, split, and join ideas

PLAIN STRINGS

With a string pattern, replace replaces only the first match. replaceAll replaces every match. A replacement can also be a function, which receives the matched text and returns the new text.

Regex comes later

Regular expressions get a whole module in Stage 8. For now, prefer plain strings. One rule to know: "aaa".replaceAll(/a/, "b") throws TypeError because a regex passed to replaceAll must be global, such as /a/g.

split(separator, limit) turns a string into an array. "a,b,c".split(",", 2) returns the first two pieces. concat combines strings, although + and template literals are more common in modern code. The next lesson, Template literals & tagged templates, goes deeper on that style.

Where you will use this

REAL HELPERS

Most front-end apps constantly clean, search, and format text: usernames, search boxes, order numbers, file names, URL slugs, labels, and masked account numbers.

Two practical helpersPop out in the code editor (opens in a new tab)JavaScript
function cleanUsername(input) {  return input.trim().toLowerCase();} function orderLabel(orderNumber) {  return "ORD-" + String(orderNumber).padStart(5, "0");} console.log(cleanUsername("  ADA  "));console.log(orderLabel(42));
String method families
FamilyWhat it returnsExample → result
Read oneA character or code unit"JS".at(-1) → "S"
ExtractA new substring"JavaScript".slice(-6) → "Script"
Search/checkAn index or boolean"Hello".includes("he") → false
CaseA case-changed copy"ß".toUpperCase() → "SS"
Pad/repeatA fixed-width or repeated copy"7".padStart(3, "0") → "007"
TrimA copy without edge whitespace" hi ".trim() → "hi"
ReplaceA changed copy"a,a".replaceAll(",", " " ) → "a a"
Split/combineAn array or combined string"a,b".split(",") → ["a", "b"]
Which method?
  • Check whether photo.png ends with .png
  • Turn order 7 into 007
  • Clean spaces around Ada
  • Read the last four characters of a card
  • Turn red,green,blue into pieces
  • Check whether a code starts with INV-
  • Extract the area code from (555) 123-4567
  • Replace every comma with a space
  • Combine first and last into one display name
Try it yourself
0 of 9 correct

Sort each real task by the kind of method family it needs.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Common misconceptions

  • “Methods edit the string.” They return new values. Assign the result if you want to keep it.
  • “includes ignores case.” It is case-sensitive. Normalize both sides when needed.
  • “slice and substring are interchangeable.” Negatives and swapped arguments differ.
  • “replace replaces everything.” With a string pattern it replaces the first match only.
  • “padStart(3, "0") adds three zeros.” The first argument is the final target length.
  • “Every visible character is one index.” Some Unicode text takes more than one code unit; the Unicode lesson covers that.

Practice exercises

5 EXERCISES
Exercise 1 · Warm-upFormat an order number

Predict the output of the starter code.

Starter codePop out in the code editor (opens in a new tab)JavaScript
const order = 7;
console.log(String(order).padStart(5, "0"));

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · PracticeNormalize user input

    What clean value should be used for comparison?

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    const typed = "  JavaScript  ";
    console.log(typed.trim().toLowerCase());

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeBuild a simple slugify function

      Keep this version simple: make "Hello World!" become a URL-friendly slug.

      Starter codePop out in the code editor (opens in a new tab)JavaScript
      function slugify(title) {
        return title.trim().toLowerCase().replaceAll(" ", "-").replaceAll("!", "");
      }
      console.log(slugify("Hello World!"));

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · ChallengeMask all but the last 4 digits

        Predict the masked value printed by the starter code.

        Starter codePop out in the code editor (opens in a new tab)JavaScript
        const digits = "123456781234";
        const last4 = digits.slice(-4);
        console.log(last4.padStart(digits.length, "*"));

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengePredict slice versus substring

          Type the two outputs, separated by a comma. Use the word empty if you prefer for the blank first line.

          Starter codePop out in the code editor (opens in a new tab)JavaScript
          const text = "JavaScript";
          console.log(text.slice(4, 0));
          console.log(text.substring(4, 0));

          Answer, then press Check. Spacing and letter case don’t matter.

            Check your understanding

            7 QUESTIONS
            String methods quiz · 7 questionsScore: first tries count
            1. Question 1 of 7What does trimming edge spaces print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              const name = "  Ada  ";
              console.log(name.trim());

              Choose an answer to see the explanation.

            2. Question 2 of 7Which method is best for reading the final four characters?

              Choose an answer to see the explanation.

            3. Question 3 of 7What does a case-sensitive includes check print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              console.log("Hello".includes("hello"));

              Choose an answer to see the explanation.

            4. Question 4 of 7What does zero-padding a ticket number print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              console.log("7".padStart(3, "0"));

              Choose an answer to see the explanation.

            5. Question 5 of 7What does replacing with a string pattern print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              console.log("red red".replace("red", "blue"));

              Choose an answer to see the explanation.

            6. Question 6 of 7What length does split with a limit print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              console.log("a,b,c".split(",", 2).length);

              Choose an answer to see the explanation.

            7. Question 7 of 7What does substring with swapped arguments print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              const text = "JavaScript";
              console.log(text.substring(4, 0));

              Choose an answer to see the explanation.

            Key takeaways

            • String methods either answer a question or return a new string, array, character, or number.
            • The original string is unchanged unless you assign the returned value somewhere.
            • slice supports negative indexes; substring clamps negatives to 0 and swaps arguments.
            • Plain searches are case-sensitive, and replace with a string pattern changes only the first match.
            • Use method families to choose quickly: read, extract, search, format, trim, replace, split, and combine.

            String methods are JavaScript’s text toolbox: small, predictable tools that read text or return a new text value.

            Up next: Template literals & tagged templates.

            CompleteFrontend Clear concepts. Working examples.