Thuta Learning
JavaScript
IntermediateProgrammingBeginner

JS String Methods

JavaScriptLesson 1425 min

What you'll walk away with

  • Explain why a string method's result must be stored for the change to take effect
  • Cut out part of a string with slice(start, end), knowing that end is excluded
  • Search text with includes, startsWith and indexOf, and normalize user input with trim and toLowerCase
  • Use replace versus replaceAll, split and join, and template literals
  • Understand that length counts UTF-16 code units

Explain it simply

Explain it simply

A string is a sequence of characters in order: "Hello World!" holds 12 characters, counting the space and the !. String methods are tools that work on that text: cutting out a piece with slice, upper-casing with toUpperCase, searching with includes, removing surrounding spaces with trim, and many more.

There is one key rule. These tools never edit the original sheet of paper; they photocopy it, edit the copy and hand the copy back. So if you want the edited text, you have to store the returned value in a variable.

Problem → Why → Solution

The problem: trim() was called, yet the login check still fails

A user types " Admin " into a role field, with spaces around it and a capital A. The developer calls trim() and toLowerCase() and expects a match with "admin". Yet the comparison stays false, and printing the input shows it unchanged. The user is told they lack permission even though they typed the right role.

role-check.js
const savedRole = "admin";
let input = "  Admin ";

input.trim();        // result is thrown away
input.toLowerCase(); // result is thrown away

console.log(input === savedRole); // false
console.log("[" + input + "]");   // [  Admin ]

Why didn't input change?

JavaScript strings are immutable: once created, their characters can never be changed. trim() and toLowerCase() each return a brand-new string, but this code stores neither result, so both vanish immediately. Only reassigning, input = input.trim().toLowerCase();, produces "admin".

Core concept: an immutable sequence and its method families

A string is an ordered sequence of characters that, like an array, starts at index 0: text[0] is the first character and text.length is the count. Unlike an array, it is immutable, so writing text[0] = "J" changes nothing. Every string method returns a new string, or a number or boolean, and leaves the original untouched.

GoalMethods
Cut out a pieceslice(start, end): end excluded, negatives allowed
Search or testincludes, startsWith, endsWith, indexOf (-1 if absent)
ReshapetoUpperCase, toLowerCase, trim, padStart
Replace or splitreplace (first match), replaceAll, split, join

slice(6, 11) takes indexes 6 through 10 and stops before 11, so the result's length is end - start, 5. slice(-3) takes the last three characters. All the search methods are case-sensitive, so "Hello".includes("hello") is false; trim() and toLowerCase() both sides before comparing user input. replace("-", "+") swaps only the first match, while replaceAll swaps every one.

Template literals, written with backticks, insert expressions such as ${name} straight into the text and may span several lines, which reads more easily than joining pieces with +.

Finally, length is not the number of characters a reader sees; it counts UTF-16 code units. "😀".length is 2, while [..."😀"].length is 1. In Myanmar text the two-syllable word "မြန်မာ" has a length of 6, because each consonant, vowel sign and mark is its own code point. Counting what a reader perceives requires an API such as Intl.Segmenter.

Because every method returns a string, calls can be chained, as in input.trim().toLowerCase(); they run left to right and each step produces a new string. Comparing two strings with === is true only when every character matches exactly. < and > compare code unit values, so every capital letter sorts before every lower-case one; to sort people's names, use a.localeCompare(b).

Mental model: methods hand back a copy
  1. The original never changes
  2. The method builds a new string
  3. It returns the new string
  4. Keep it by storing it in a variable

A line like text.trim(); that ignores the result does nothing at all.

General pattern

javascript
const result = original.method(arguments); // original stays the same

value = value.trim().toLowerCase();          // chain, then reassign

original.slice(startIndex, endIndex);        // endIndex is excluded
original.includes(searchText);               // true or false
original.split(separator).join(glue);        // string -> array -> string

const message = `Text with ${expression} inside`;

Store a method's result in a new variable or back in the original one. Methods can be chained, and a template literal inserts values with ${} inside backticks.

Example: trying methods on "Hello World!"

This example tries length, slice, toUpperCase and includes on one string, then prints the original text on the last line. You will see that after four method calls the original is still the same.

string-methods.js
let text = "Hello World!";
let length = text.length;
let part = text.slice(6, 11); // from index 6 to 10
let upper = text.toUpperCase();

console.log("Length: " + length);
console.log("Part: " + part);
console.log("Upper: " + upper);
console.log("Has World? " + text.includes("World"));
console.log("Original: " + text);

Code breakdown

  1. Line 2let length = text.length;

    length is a property, not a method, so there are no parentheses. "Hello World!" has 12 characters, counting the space and the !.

  2. Line 3let part = text.slice(6, 11); // from index 6 to 10

    Index 6 is "W", and index 11, the "!", is excluded, giving "World". The result's length is 11 - 6 = 5.

  3. Line 4let upper = text.toUpperCase();

    Stores a new upper-case string in upper; text itself is not changed.

  4. Line 9console.log("Has World? " + text.includes("World"));

    includes returns a boolean. Searching for "world" in lower case would give false, because the search is case-sensitive.

  5. Line 10console.log("Original: " + text);

    Even after four method calls, text is still "Hello World!", which is immutability in action.

You should see
Length: 12
Part: World
Upper: HELLO WORLD!
Has World? true
Original: Hello World!

Template literals, split/join, replaceAll and Unicode

This snippet lets you run each family of methods from the concept section. split(",") turns a CSV line into an array and join(" | ") glues it back into a string. padStart pads numbers such as invoice numbers to a shape like 007, and the last line shows two different lengths for a string containing an emoji.

more-strings.js
const name = "Mya";
const items = 3;
console.log(`Hi ${name}, you have ${items} items in your cart`);

const fruits = "apple,banana,cherry".split(",");
console.log(fruits, fruits.join(" | "));

const code = "a-b-c";
console.log(code.replace("-", "+"), code.replaceAll("-", "+")); // a+b-c a+b+c
console.log("7".padStart(3, "0"));                               // 007
console.log("report.pdf".endsWith(".pdf"), "Hello".indexOf("z")); // true -1
console.log("Hello".slice(-3));                                  // llo

const withEmoji = "hi😀";
console.log(withEmoji.length, [...withEmoji].length); // 4 3

In real projects

Where string methods show up in real projects

Every sign-up form normalizes email and username with trim() and toLowerCase() before saving them, so "Mya@Example.com " and "mya@example.com" never become two accounts. The display name the user typed is still shown as written, so apps store a comparison value and a display value separately. For Unicode text, plain lowercasing is not always enough; in Turkish, for instance, "I".toLocaleLowerCase("tr") gives "ı", so tests should include empty strings and emoji or Myanmar input too.

Blogs and shops build URL slugs such as "learn-javascript-strings" from titles with a chain of trim, toLowerCase, split and join. Search boxes test with includes, and card previews cut long text with slice and add "...". In fields with a character limit, such as SMS or social posts, remember that length may count a single emoji as two.

Common mistakes

Common mistakes

1. Not storing the method's result

As in the problem section, name.trim(); on its own line changes nothing. Reassign with name = name.trim();, or keep the result in a new variable such as const cleanName = name.trim();.

2. Expecting replace to change every match

"2024-01-15".replace("-", "/") gives "2024/01-15", because with a string pattern replace swaps only the first match. Use replaceAll("-", "/") to change them all.

3. Thinking slice includes the end index

"JavaScript".slice(0, 4) is "Java"; index 4, the "S", is not included. Read it as "from start up to, but not including, end", and check that the result's length is end - start.

4. Enforcing a character limit with length alone

Limiting a bio to "10 characters" with length means five emoji already use up the limit, since a typical emoji counts as 2. Cutting with slice can also split an emoji in half and leave a broken character behind. Count with [...text] or Intl.Segmenter to match what the user sees.

Best practices

Best practices

  • Normalize user input once, at the boundary where it enters the program, so the rest of the code only sees clean values.
  • Prefer template literals over + when mixing text and variables; forgotten spaces become much rarer.
  • Keep a value for searching and comparing separate from the value you display, and never destroy what the user typed.

Mini challenge

Mini challenge: username, slug and preview

Write three string helper functions that clean up user input and titles.

  • normalizeUsername(raw): trim the surrounding spaces and lower-case it
  • makeSlug(title): lower-case, strip "!", "?" and ",", and join the words with "-" even when they are separated by several spaces
  • previewText(text, max): return text unchanged if it fits, otherwise slice(0, max), trimEnd it and add "..."
  • Every function returns a new string; print the original argument to show it did not change
text-helpers.js
function normalizeUsername(raw) {
  // TODO: remove surrounding spaces and lower-case
}

function makeSlug(title) {
  // TODO: lower-case and strip "!", "?" and ","
  // TODO: split on spaces, drop empty pieces, join with "-"
}

function previewText(text, max) {
  // TODO: unchanged if short enough, otherwise cut, trimEnd and add "..."
}

const title = "  Learn JavaScript   Strings! ";
// TODO: print normalizeUsername("  MyaMya "), makeSlug(title),
// two previewText examples, and the original title in brackets

Expected: myamya learn-javascript-strings String methods... Short [ Learn JavaScript Strings! ]

Show hint

split(" ") produces empty "" items where spaces are doubled. Keep only word !== "" with filter before calling join("-").

Show solution
text-helpers.js
function normalizeUsername(raw) {
  return raw.trim().toLowerCase();
}

function makeSlug(title) {
  const cleaned = title
    .toLowerCase()
    .replaceAll("!", "")
    .replaceAll("?", "")
    .replaceAll(",", "");
  const words = cleaned.split(" ").filter(function (word) {
    return word !== "";
  });
  return words.join("-");
}

function previewText(text, max) {
  if (text.length <= max) return text;
  return text.slice(0, max).trimEnd() + "...";
}

const title = "  Learn JavaScript   Strings! ";
console.log(normalizeUsername("  MyaMya "));
console.log(makeSlug(title));
console.log(previewText("String methods return new strings", 15));
console.log(previewText("Short", 15));
console.log("[" + title + "]");

Quick quiz 1 / 3

What does let s = "hello"; s.toUpperCase(); console.log(s); print?

Quick quiz 2 / 3

What does "JavaScript".slice(4, 7) return?

Quick quiz 3 / 3

What does "a-b-c".replace("-", "+") return?

What to remember

  • Strings are immutable and every method returns a new string, so store the result.
  • slice(start, end) excludes end, and negative indexes count from the end.
  • Searches are case-sensitive, so trim() and toLowerCase() input before comparing.
  • replace swaps the first match and replaceAll swaps every match, while split and join convert between strings and arrays.
  • length counts UTF-16 code units, so it can differ from the visible character count for emoji and Myanmar text.

MDN — JavaScript Guide — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

JS String Methods | Thuta Learning