completefrontend
Open lab My progress
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 methodName the job first (read, copy out, search, pad, trim, replace, or split), then pick a method that does it.
  • 02
    Guess tricky resultsSay how slice and substring differ, why searches care about capitals, and why replace swaps only the first match.
  • 03
    Write small text helpersClean what a user typed, add zeros to the front of an order number, make a web address part from a title, and hide most of a card number.

A toolbox for text

INTERACTIVE

A string is text, like "Asha" or "photo.png". JavaScript gives every string a set of built-in tools. These tools are called string methods.

You call a method with a dot, its name, and round brackets: name.trim(). Some methods need extra values inside the brackets, like file.endsWith(".png"). These extra values are called arguments.

Each method does one of three jobs:

  • It answers a question, such as "Does this text contain a comma?"
  • It copies out a piece of the text, such as the first four letters.
  • It makes a new string with a change, such as all capital letters.

The answer a method gives back is called its return value.

You learned one rule in the Strings lesson: a string can't be changed after it is made. The word for this is immutable. So a string method never edits the original string. It makes a new value and gives it back. If you want to keep that new value, store it in a variable.

The box name holds " Ada " with spaces at both ends. An arrow labelled .trim() leads to a new card, "Ada". The box still holds the old string."  Ada  "nameunchanged.trim()"Ada"a new string
name.trim() reads the string in the box and makes a new string, "Ada". The box still holds the old string, with its spaces. To keep the new string, store it: name = name.trim().
Real-life analogyString methods are a photocopier with buttons

Picture a photocopier with buttons like "cut off the blank edges" and "print in capital letters". You put in a sign and press a button. The machine prints a new sheet. The sign you put in stays the same.

In real life: The original sheet of paper
In JavaScript: The original string
In real life: A copy with the blank edges cut off
In JavaScript: text.trim()
In real life: A copy printed in capital letters
In JavaScript: text.toUpperCase()
In real life: The original sheet stays in the tray
In JavaScript: The original string does not change
String workbench
A method gives back 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 gives back "Hello,·World!". The original is still "··Hello,·World!··", because string methods make a new value.

Spaces are shown as · so you can see what trimming, padding, and splitting do. Reset puts back the starting text and method.

Pick a method in the workbench and compare the original with the result. The result changes with each method. The original string stays the same every time.

Try trim(), slice(), includes(), padStart(), replaceAll(), and split(). Each one is explained later in this lesson.

Read one character or cut out a piece

STEP THROUGH

Each character in a string has a position number, called an index. Counting starts at 0, just like in arrays. In "tea", t is at index 0 and a is at index 2.

Three methods read the character at one index. Each gives back a different kind of answer:

  • at(index) gives the character. A negative index counts from the end.
  • charAt(index) also gives the character. It does not count from the end.
  • charCodeAt(index) gives a number: the code JavaScript stores for that character.
Read index 0 in three waysPop out in the code editor (opens in a new tab)JavaScript
const drink = "tea";console.log(drink.at(0));console.log(drink.charAt(-1));console.log(drink.charCodeAt(0));

Line 2 reads index 0 with at, so it prints t.

Line 3 asks charAt for index -1. charAt doesn't count from the end, so there is no character there. It gives back an empty string, "": a string with no characters. The console shows a blank line.

Line 4 prints 116. JavaScript stores each character as a number, called a UTF-16 code unit. 116 is the number for a small t. You will learn more about these numbers in the Unicode & string internals lesson.

Here are the same three methods on the word "JavaScript":

  • "JavaScript".at(0) gives "J". at(-1) gives the last character, "t".
  • charAt(0) also gives "J". But charAt(-1) gives an empty string.
  • charCodeAt(0) gives 74, the number for a capital J.

When you want the last character, use at(-1).

To copy out more than one character, use slice(start, end). It copies from the start index up to the end index. The character at end is not included. If you leave out end, it copies to the end of the string. A negative number counts back from the end.

The string JavaScript drawn as ten letter cards with index 0 to 9 under them. A dashed cut sits before index 4. slice(0, 4) gives "Java", the cards on the left. slice(-6) gives "Script", the last six cards on the right.slice(0, 4)slice(-6)J0a1v2a3S4c5r6i7p8t9index"Java""Script"
slice(0, 4) copies from index 0 up to index 4, but not index 4 itself, so it gives "Java". slice(-6) counts 6 back from the end, which lands on index 4, and copies to the end: "Script".
Real-life analogyslice cuts a strip out of a paper banner

Picture the word JavaScript printed on a long paper banner. There is a pencil mark before each letter. To cut, you pick a start mark and an end mark. You get the strip between them.

In real life: Pencil marks between the 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 6 marks back from the right edge
In JavaScript: text.slice(-6)
In real life: Start mark is right of the end mark, so nothing to cut
In JavaScript: text.slice(4, 0) gives ""

A second method, substring(start, end), also copies a piece. It works like slice for normal numbers. The two give different results in two cases:

  • A negative number. slice counts it from the end. substring treats it as 0.
  • A start that is bigger than the end. slice gives an empty string. substring swaps the two numbers first.

Step through both cases below. Guess what each line prints before you press Next.

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

Guess the two printed lines. Then step through to see what slice and substring do with the same numbers.

Running in
  1. script
Next: line 1
const piece = text.slice(-6);const other = text.substring(-6);console.log(piece);console.log(other);
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
Choose the two numbers

Changing the numbers starts the step-through again from line 1.

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 one of two questions: "Where is it?" or "Is it there?"

  • indexOf(text) gives the index where text first appears. If it is not there, it gives -1.
  • lastIndexOf(text) does the same, but looks for the last place it appears.
  • includes(text) gives true if text is there, and false if not.

A value that is always true or false is called a boolean.

These searches are case-sensitive. That means a capital letter and a small letter count as different characters. So "Hello".includes("hello") gives false.

People type in any mix of capitals. To search what they type, make both strings lowercase first: text.toLowerCase().includes(query.toLowerCase()).

Left: "Hello".includes("hello") gives false, because capital H and small h are different. Right: after making both lowercase, "hello".includes("hello") gives true.as typed"Hello".includes("hello")falseH is not hboth made lowercase"hello".includes("hello")truematch found
To JavaScript, a capital H and a small h are different characters, so the left search finds nothing. On the right, both strings were made lowercase first, so the search finds a match.

Two more methods check only the start or the end of a string:

  • startsWith(text) gives true if the string begins with text.
  • endsWith(text) gives true if the string ends with text.

"invoice.pdf".endsWith(".pdf") gives true. It is easier to read than cutting off the last four characters yourself.

Both methods take an optional second argument. "Optional" means you can leave it out:

  • For startsWith, it is the index where the check begins.
  • For endsWith, it is how many characters from the front to look at. The check treats that as the end of the string.
Check the start or end of part of a stringPop out in the code editor (opens in a new tab)JavaScript
const code = "INV-42";console.log(code.startsWith("42", 4));console.log(code.endsWith("INV", 3));console.log(code.endsWith("-42"));

Line 2 starts the check at index 4. That is where 42 begins, so it prints true.

Line 3 looks at only the first 3 characters, INV. Those characters end with INV, so it prints true.

Line 4 has no second argument, so it checks the real end of the string. The string ends with -42, so it prints true.

Step through the search and replace code below. Pick a setting, guess the output, then press Next.

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

Pick a setting and guess the output. Then step through the real method calls.

Running in
  1. script
Next: line 1
const first = text.indexOf("Hello", 1);const hasLower = text.includes("hello");const fixed = text.toLowerCase().includes("hello");console.log(first, hasLower, fixed);
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
Choose what to step through

The code changes with the setting. Guess 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 case on a copy

toUpperCase() makes a copy in capital letters. toLowerCase() makes a copy in small letters. The original string does not change.

You will use these for two jobs:

  • Showing text in a different style, such as a heading in capitals.
  • Comparing text the user typed, where capitals should not matter.
Make a capital-letter copy for a headingPop out in the code editor (opens in a new tab)JavaScript
const name = "Asha";const heading = name.toUpperCase();console.log(heading);console.log(name);

Line 2 makes a copy in capitals and stores it in heading. Line 3 prints ASHA. Line 4 prints the original, Asha, which did not change.

Keep the original when the way it is written matters. Use the changed copy only where you need it.

Changing case can change the length

Some languages have letters with special case rules, and JavaScript follows those rules. The German letter ß has no single capital form, so "ß".toUpperCase() gives SS, two letters.

The rules can also depend on the language. A locale names a language and a region, such as "tr-TR" for Turkish in Turkey. Methods with Locale in their name use those rules. On a computer that has Turkish language data, "i".toLocaleUpperCase("tr-TR") gives İ, a capital I with a dot.

Use the locale methods for text that people read in their own language. For text your code controls, like IDs, file endings, and comparisons, use plain toLowerCase(). Its result is the same everywhere.

Pad, repeat, and trim text

EXAMPLES

Three methods make a string a set length or repeat it:

  • padStart(length, fill) adds fill characters to the front until the string is length characters long.
  • padEnd(length, fill) does the same, but adds them to the end.
  • repeat(count) joins count copies of the whole string.

Some examples:

  • "7".padStart(3, "0") gives "007".
  • "1234".padStart(8, "*") gives "****1234".
  • "ab".repeat(3) gives "ababab".

Whitespace means characters you can't see: spaces, tabs, new lines, and non-breaking spaces. A non-breaking space is a space that keeps two words on the same line.

Three methods remove whitespace from the edges of a string:

  • trim() removes it from both ends.
  • trimStart() removes it from the start only.
  • trimEnd() removes it from the end only.

This string has tabs (\t), new lines (\n), and spaces around the word hi: "\t\n  hi  \n". Trimming it in real JavaScript leaves "hi".

The padding number is the final lengthPop out in the code editor (opens in a new tab)JavaScript
const ticket = "7";console.log(ticket.padStart(3, "0"));console.log("ha".repeat(2));console.log("tea".padEnd(5, "."));

Line 2 pads the ticket to 3 characters, so it prints 007. Line 3 repeats the whole string twice and prints haha. Line 4 pads on the right to 5 characters and prints tea...

The first number you give padStart or padEnd is the final length. It is not how many characters to add.

Replace, split, and join text

PLAIN STRINGS

replace(find, newText) makes a copy where find is swapped for newText. When find is a string, only the first match is swapped.

replaceAll(find, newText) swaps every match.

Left: "red red" with replace("red", "blue") gives "blue red". Only the first red changes. Right: "red red" with replaceAll("red", "blue") gives "blue blue". Every red changes..replace("red", "blue")"red red""blue red"first match only.replaceAll("red", "blue")"red red""blue blue"every match
Both start from the same string, "red red". replace changes only the first red. replaceAll changes every red. Neither one changes the original string.

The second argument can also be a function. JavaScript calls it with the matched text, and uses what the function returns as the new text. To see one, pick the replace setting in the step-through above.

Patterns come later

A regular expression, or regex, is a pattern for finding text, written between slashes like /a/. Regexes get a whole module in Stage 8. For now, use plain strings.

One rule to know now: "aaa".replaceAll(/a/, "b") throws a TypeError. A regex given to replaceAll must end with g, like /a/g. The g means "find every match".

split(separator) cuts a string into pieces and gives back an array of those pieces. The separator is the text to cut at, such as a comma. A second argument, the limit, says how many pieces to keep. "a,b,c".split(",", 2) gives ["a", "b"].

concat joins strings into one. Most code joins strings with + or with a template literal instead. A template literal is a string in backticks, like `Hi, ${name}`. The next lesson, Template literals & tagged templates, covers them.

Split tags into pieces and join a namePop out in the code editor (opens in a new tab)JavaScript
const tags = "js,web,css";const pieces = tags.split(",");const displayName = "Asha".concat(" ", "Khan");console.log(pieces.length);console.log(displayName);

Line 2 cuts the tags at each comma. That makes an array of 3 pieces, so line 4 prints 3.

Line 3 starts with "Asha" and joins a space and "Khan" to it. Line 5 prints Asha Khan.

Use split when you need separate pieces. Use concat, +, or a template literal when you need one string.

Where you will use this

REAL HELPERS

Almost every website cleans, searches, and formats text. For example:

  • usernames and search boxes
  • order numbers and labels
  • file names and web addresses
  • card numbers where only the last four digits show

A small function that does one of these jobs is often called a helper.

Two helpers: clean a name and label an orderPop 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));

Line 2 removes the outside spaces, then makes the copy lowercase. Line 9 prints ada. Use this cleaned name for comparing. If the page should show the name the way the user wrote it, keep the original for that.

Line 6 turns the number into a string with String(), then pads it to 5 characters. Line 10 prints ORD-00042. Every order label now has the same length, so a list of them lines up and sorts in order.

Search products without caring about capitalsPop out in the code editor (opens in a new tab)JavaScript
const products = ["Tea", "Coffee", "Toast"];const typed = " tea ".trim().toLowerCase();const matches = products.filter((product) => product.toLowerCase().includes(typed));console.log(matches.length);console.log(matches[0]);

Line 2 cleans what the user typed: no outside spaces, all lowercase.

Line 3 uses the array method filter. It keeps each product whose lowercase copy includes the search text. Capitals don't matter, because both sides are lowercase.

Line 4 prints 1, the number of matches. Line 5 prints Tea with its capital T. The product names in the array never change. Only the copies used for comparing are lowercase.

Check a file endingPop out in the code editor (opens in a new tab)JavaScript
const fileName = "avatar.PNG";const extension = fileName.slice(fileName.lastIndexOf(".")).toLowerCase();console.log(extension);console.log(extension === ".png");

Line 2 calls three methods, one after another:

  • lastIndexOf(".") finds the index of the last dot.
  • slice copies from that dot to the end: ".PNG".
  • toLowerCase makes that copy lowercase, so capitals don't matter.

Line 3 prints .png and line 4 prints true.

This check only gives the user quick feedback on the page. It does not make uploads safe. The server must check uploaded files too.

The table below sorts string methods by the kind of job they do. Read each row as: this kind of job gives back this kind of value, for example this.

Kinds of string methods and what they give back
Kind of jobWhat do you get back?Example and its result
Read one characterOne character, or the number stored for it."JS".at(-1) gives "S".
Copy out a pieceA new, shorter string."JavaScript".slice(-6) gives "Script".
Search or checkAn index, or true or false."Hello".includes("he") gives false.
Change caseA copy in capital or small letters."ß".toUpperCase() gives "SS".
Pad or repeatA copy with a set length, or repeated."7".padStart(3, "0") gives "007".
TrimA copy with no whitespace at the edges." hi ".trim() gives "hi".
ReplaceA copy with some text swapped."a,a".replaceAll(",", " ") gives "a a".
Split or joinAn array of pieces, or one joined string."a,b".split(",") gives ["a", "b"].
Which method?
  • Check if photo.png ends with .png
  • Turn order 7 into 007
  • Remove the spaces around Ada
  • Get the last four digits of a card number
  • Turn red,green,blue into separate pieces
  • Check if a code starts with INV-
  • Get the area code from (555) 123-4567
  • Swap every comma for a space
  • Join first and last into one name to show
Try it yourself
0 of 9 correct

Each card is a real task. Sort it into the kind of method that does the job.

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

Common misconceptions

Trim cleans the edges, not the middlePop out in the code editor (opens in a new tab)JavaScript
const title = "  tea party  ";console.log(title.trim());console.log(title.includes("tea party"));console.log(String(42).padStart(4, "0"));

Line 2 removes only the spaces at the two ends, so it prints tea party. The space between the words stays.

Line 3 prints true: the words tea party, with their space, are still inside title.

Line 4 turns the number 42 into the string "42" first. Numbers don't have padStart; strings do. It prints 0042.

Here are the mistakes people make most often, and what is really true:

  • "Methods change the string." They give back a new value. Store the result if you want to keep it.
  • "includes ignores capitals." It is case-sensitive. Make both strings lowercase first when capitals should not matter.
  • "slice and substring are the same." They differ for negative numbers and for a start bigger than the end.
  • "replace swaps every match." With a string to find, it swaps only the first match. Use replaceAll for every match.
  • "padStart(3, "0") adds three zeros." The 3 is the final length. "7" gets two zeros.
  • "Every character you see is one index." Some characters, like many emoji, take two indexes. The Unicode lesson explains why.

Practice exercises

6 EXERCISES
Exercise 1 · Warm-upFormat an order number

Guess what the starter code prints.

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 · PracticeClean what a user typed

    What cleaned value does the starter code print?

    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 · PracticeTurn a title into a web address part

      A slug is the part of a web address made from a title, like hello-world. It has small letters and dashes, and no spaces. Make "Hello World!" into a slug, and type what the code prints.

      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 · ChallengeHide all but the last 4 digits

        Guess the hidden card number that the starter code prints.

        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 · ChallengeGuess slice and substring

          Type the two outputs, with a comma between them. If an output is a blank line, you can type the word empty for it.

          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.

            Exercise 6 · ChallengeCheck a profile email

            A profile form should accept an email only if it ends with @example.com. Guess the true or false that the code prints.

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

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

              Check your understanding

              8 QUESTIONS
              String methods quiz · 8 questionsScore: first tries count
              1. Question 1 of 8What does this code print after trimming?

                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 8Which call gives the last four characters of a string?

                Choose an answer to see the explanation.

              3. Question 3 of 8What does this 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 8What does padding a ticket number with zeros 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 8What does replace with a string 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 8How many pieces does split with a limit keep?

                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 8What does substring print when start is bigger than end?

                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.

              8. Question 8 of 8What does startsWith with a start index print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                const code = "INV-42";
                console.log(code.startsWith("42", 4));

                Choose an answer to see the explanation.

              Key takeaways

              • A string method either answers a question or gives back a new value: a string, an array, a character, a number, or true/false.
              • The original string never changes. Store the result in a variable to keep it.
              • slice counts negative numbers from the end. substring treats them as 0, and swaps its two numbers when the start is bigger.
              • Searches are case-sensitive. replace with a string swaps only the first match.
              • To pick a method, first name the job: read, copy out, search, change case, pad, trim, replace, or split and join.

              String methods are JavaScript's tools for text. Each one reads a string or gives back a new value; none of them changes the original.

              Up next: Template literals & tagged templates.

              CompleteFrontend Clear concepts. Working examples.