Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 156 ยท Data Types

String Methods

Master the JavaScript string methods you use every day - slice, indexOf, includes, startsWith, trim, split, replace, replaceAll, padStart, repeat and at().

Strings come with dozens of built-in methods: functions you call on a string with a dot, such as email.trim() or title.toUpperCase(). They let you search text, cut pieces out of it, clean it up, split it apart and build it into new shapes.

This lesson covers the methods you'll reach for every day, grouped by what they do. Remember the golden rule from Strings: strings are immutable, so every method returns a new string (or another value) and leaves the original untouched. If you want to keep the result, store it.

Extracting part of a string

slice(start, end)

slice() copies a section of a string. It starts at index start and stops just before index end. If you leave out end, it goes to the end of the string. Negative numbers count from the end, which makes slice() very flexible:

JS Cutting strings with slice()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A handy way to think about start and end: they mark the gaps between characters. slice(0, 7) takes everything between gap 0 and gap 7, which is exactly 7 characters. The length of the result is always end - start.

substring(start, end)

substring() is an older method that works almost the same way, with two differences: negative numbers are treated as 0, and if start is bigger than end, the two are swapped. Those rules make mistakes harder to spot, so prefer slice() in new code. You'll still see substring() in existing code, so it's good to recognize it. (There's also a deprecated substr(); avoid it.)

at(index) and charAt(index)

at() returns the character at a position and accepts negative indexes: "hello".at(-1) is "o". It arrived in ES2022 and works in all modern browsers. The older charAt() does the same for positive indexes but returns an empty string instead of undefined when the index is out of range.

Searching

Several methods answer "is this text in there, and where?":

  • includes(text) โ€” true if the string contains text anywhere.
  • startsWith(text) and endsWith(text) โ€” true if it begins or ends with text.
  • indexOf(text) โ€” the index of the first match, or -1 if there's none.
  • lastIndexOf(text) โ€” the index of the last match, or -1.

All of them are case-sensitive.

JS Searching inside strings

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Use includes(), startsWith() or endsWith() when you only need a yes or no answer: they read like plain English. Use indexOf() when you need the position, usually to slice() around it. A common old-style check is text.indexOf("x") !== -1; text.includes("x") says the same thing more clearly.

To search without caring about case, convert both sides first: title.toLowerCase().includes(query.toLowerCase()).

Changing case

toUpperCase() and toLowerCase() return the whole string in capitals or small letters. They're most useful for comparisons, so that "Yes", "YES" and "yes" all count as the same answer:

JavaScript
const reply = "YeS";
if (reply.toLowerCase() === "yes") {
  console.log("Confirmed");
}

For languages with special casing rules, such as Turkish, there are also toLocaleUpperCase() and toLocaleLowerCase(), which accept a language code like "tr".

Removing whitespace

People often type extra spaces before or after their input, and text from files can end with line breaks. The trim methods remove whitespace (spaces, tabs and line breaks) from the edges of a string, but never from the middle:

  • trim() โ€” both ends
  • trimStart() โ€” the beginning only
  • trimEnd() โ€” the end only
JavaScript
const raw = "   [email protected] \n";
console.log(raw.trim());       // "[email protected]"
console.log(raw.trimStart());  // "[email protected] \n"

Trimming should be the first thing you do with almost any text a user types, before checking whether it's empty or comparing it.

Splitting and joining

split(separator) breaks a string into an array of pieces wherever the separator appears. Its partner, the array method join(separator), glues an array back into a string:

JS split() and join()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The slug example shows method chaining: each method returns a value, so you can immediately call another method on it. Read the chain from left to right: trim, then lowercase, then split into words, then join with hyphens. You'll learn much more about arrays and join() in Arrays.

If the separator never appears, split() returns an array with the whole string as its only item. For text containing emoji, [...text] splits into characters more safely than split("").

Replacing text

replace(search, replacement) returns a new string with the first match replaced. replaceAll(search, replacement) replaces every match. replaceAll() was added in ES2021 and works in all modern browsers.

JS replace() and replaceAll()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Both methods also accept a regular expression as the search pattern, which lets you match flexible patterns such as "any digit" or "cat in any case". That's a powerful tool with its own lessons: Regular Expressions and Regular Expressions in Practice.

Padding and repeating

padStart(length, filler) adds characters to the start of a string until it reaches the given length. padEnd() adds them to the end. If the string is already long enough, it's returned unchanged. repeat(count) repeats a string a number of times.

JS padStart, padEnd and repeat

Press Run (or Ctrl + Enter) to see the console output here.

No output.

padStart() only works on strings, so convert numbers with String() first. When you leave out the filler, it pads with spaces, which is how the prices above line up on the right. (The const [item, price] part unpacks each row into two variables; that's destructuring.)

Quick reference

Method Returns Example
slice(start, end) Part of the string "hello".slice(1, 3) โ†’ "el"
at(index) One character (negative allowed) "hello".at(-1) โ†’ "o"
indexOf(text) First position or -1 "hello".indexOf("l") โ†’ 2
includes(text) true or false "hello".includes("ell") โ†’ true
startsWith(text) / endsWith(text) true or false "hello".startsWith("he") โ†’ true
toUpperCase() / toLowerCase() A new string "Hi".toUpperCase() โ†’ "HI"
trim() A new string " hi ".trim() โ†’ "hi"
split(sep) An array "a,b".split(",") โ†’ ["a", "b"]
replace(a, b) / replaceAll(a, b) A new string "aa".replaceAll("a", "b") โ†’ "bb"
padStart(len, fill) A new string "5".padStart(3, "0") โ†’ "005"
repeat(n) A new string "ab".repeat(2) โ†’ "abab"

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is "keyboard".slice(3, 6)?

    Counting from 0, index 3 is "b". slice() starts there and stops before index 6, so it returns three characters: "boa".
  2. 2. What does "Hello".indexOf("z") return?

    indexOf() returns -1 when the text isn't found. Use includes() if you only need true or false.
  3. 3. You want to replace every comma in a string with a semicolon. Which call does that?

    replace() with a string only changes the first match. replaceAll() changes all of them. (text.split(",").join(";") would also work.)
  4. 4. What is "9".padStart(3, "0")?

    padStart() adds the filler to the start until the string is 3 characters long.
  5. 5. After const name = " Lea "; name.trim();, what is name?

    Strings are immutable, and the trimmed result was never stored. Write const clean = name.trim(); to keep it.

Summary

  • String methods never change the original string: they return new values, so store the result.
  • Extract with slice() (supports negative indexes) and at(). Prefer slice() over substring().
  • Search with includes(), startsWith(), endsWith(), and indexOf()/lastIndexOf(), which return -1 when nothing is found. All are case-sensitive.
  • Clean up input with trim() and normalize case with toLowerCase() before comparing.
  • split() turns a string into an array; join() turns it back. Methods can be chained.
  • replace() changes the first match, replaceAll() every match.
  • padStart(), padEnd() and repeat() help format output.

Next: Template Literals โ€” building strings with embedded values.