String Methods

The built-in tools for reading, searching, and reshaping text.

What is it?

Text is everywhere in a program: a name, a message, a URL. You often need to ask small questions about it. How long is it? Does it contain this word? What does it look like in uppercase? Strings have built-in methods for these, so you rarely process text character by character.

The ones you'll use most: length (a property, not a method), slice, includes, split, trim, replace, and template literals for building strings from pieces.

Explain like I'm 10

If a string is a train of cars, string methods are the inspector's tools: one counts the cars (length), one pulls out a section (slice), one checks whether a certain car exists (includes), one uncouples the train into single cars (split).

Examples

Common string operations

const message = "  Hello, World!  ";

console.log(message.length);            // 18 (includes the spaces)
console.log(message.trim());            // "Hello, World!"
console.log(message.includes("World")); // true
console.log(message.toLowerCase());     // "  hello, world!  "

const name = "Amara";
console.log(`Hi, ${name}!`);             // "Hi, Amara!" — a template literal

const parts = "2026-08-29".split("-");  // ["2026", "08", "29"]

Searching and replacing within a string

const sentence = "The cat sat on the mat";

console.log(sentence.indexOf("cat"));         // 4
console.log(sentence.replace("cat", "dog"));  // "The dog sat on the mat"
console.log(sentence.startsWith("The"));      // true
console.log(sentence.slice(4, 7));            // "cat"

indexOf finds a position, replace swaps text, startsWith checks the beginning, and slice pulls out a substring by position. None of them change the original string.

How it works

Strings are immutable, so every method returns a new string (or array) instead of changing the original. trim() doesn't change message; it returns a trimmed copy. length is a property, not a method, so you read it without parentheses.

Why does it exist?

Walking through text character by character to search or reshape it is slow to write and easy to get wrong. Built-in methods handle most everyday text tasks in one clear, well-tested call.

When to use it

Use them to validate, search, format or reshape text: checking a username's length, confirming an email contains "@", splitting a comma-separated list, or building a message with a template literal.

When not to use it

For heavy text processing (parsing complex formats, matching flexible patterns), plain string methods get unwieldy; use a regular expression. And building a large string from many small concatenations in a loop is slower than collecting pieces in an array and joining once.

Common mistakes

  • Forgetting that string methods don't mutate — str.trim() does nothing unless you use or store its return value.

  • Using + to build long strings piece by piece inside a loop instead of a template literal or joining an array.

  • Forgetting that .length counts UTF-16 code units, which can differ from the number of visible characters for some emoji and special characters.

Practice exercises

  1. Easy:

    Use .toUpperCase() and .length to print a name in all caps along with its length.

  2. Medium:

    Use .split() and .join() to reverse the order of words in a sentence.

  3. Hard:

    Write a function that checks whether a string is a valid-looking email (contains exactly one "@" and at least one "." after it) using only string methods.

Interview questions

Why do string methods like `trim()` or `toUpperCase()` never modify the original string?

Strings are immutable. Every string method returns a new string; you can't change an existing string's characters in place.

What does this log? `let str = "hello"; str.toUpperCase(); console.log(str);`

"hello", unchanged. toUpperCase() returns a new string, but its result is thrown away. You'd need str = str.toUpperCase();.

What's the difference between `slice()` and `substring()` on a string?

Both extract a range. slice() accepts negative indexes, counting from the end. substring() treats negatives as 0 and swaps the arguments if start is greater than end.

What does this log? `const s = "Hello, World!"; console.log(s.slice(-6));`

"World!". A negative index in slice() counts back from the end, so -6 starts six characters before the end.

Are string comparisons with `includes()`, `startsWith()`, and `endsWith()` case-sensitive?

Yes; they compare exact characters, so "Hello".includes("hello") is false. For a case-insensitive check, call .toLowerCase() (or .toUpperCase()) on both sides first.

What does this log? `console.log("Hello".includes("hello"));`

false. "H" and "h" are different code points, and includes() doesn't normalize case.

What can a template literal do that regular quoted strings can't?

It can span multiple lines without escapes, and it can embed any expression in a ${...} placeholder, which is evaluated and turned into a string. That replaces manual + concatenation.

What does `String(null)` return, compared to `null + ""`?

Both give "null": String() and + coercion use the same conversion rules for primitives. JSON.stringify(null) also returns "null", but for an unrelated reason: it serializes the JSON value null.

What is a tagged template literal?

A function written directly before a template literal. Instead of interpolating automatically, the tag function receives the literal string pieces and the interpolated values separately, so it can process or escape them before building the final string.

What does this log, and why? `console.log("2" > "10");`

true. Comparing strings with >/< goes character by character by Unicode code point, not numerically. "2" is greater than "1", so the comparison stops there.

What does this log? `console.log(1 + "1"); console.log("1" + 1); console.log(1 + 1 + "1"); console.log("1" + 1 + 1);`

"11", "11", "21", "111". + runs left to right, and any + with a string operand concatenates. 1 + 1 + "1" adds first (2), then joins "1". "1" + 1 + 1 concatenates from the first +, so every following + does too.

What do `padStart()` and `padEnd()` do?

They add a fill string (repeated as needed) to the start or end until the string reaches a target length. Common for zero-padding numbers or aligning text in columns.

What does this log? `console.log("5".padStart(3, "0"));`

"005". padStart adds "0"s to the front until the length is 3.

Why might `.length` not match the number of visible characters in a string?

.length counts UTF-16 code units, not visible characters (grapheme clusters). Characters outside the Basic Multilingual Plane, including many emoji, use two code units (a surrogate pair), so they count as 2 but display as one.

What does `console.log("😀".length);` log, and why isn't it `1`?

2. That emoji is outside the Basic Multilingual Plane and is stored as a UTF-16 surrogate pair (two 16-bit code units). .length counts code units, not visible characters.

What's the difference between `trim()`, `trimStart()`, and `trimEnd()`?

trim() removes whitespace from both ends; trimStart() only from the start; trimEnd() only from the end.

What does this log? `console.log("abc".split(""));`

["a", "b", "c"]. Splitting on an empty string splits between every character.

What's the difference between `replace()` and `replaceAll()`?

replace(search, value) with a plain string replaces only the first match; to replace all with replace, you need a regex with the global flag. replaceAll() replaces every match, even with a plain string.

What does this log? `console.log("cat cat cat".replace("cat", "dog"));`

"dog cat cat". With a plain string (not a global regex), replace() stops after the first match.

Why is repeatedly concatenating strings with `+=` inside a large loop considered inefficient?

Strings are immutable, so each += creates a new string and copies all previous characters: roughly O(n squared) copying for n concatenations. Pushing pieces into an array and calling .join("") once avoids that.

Why can you safely compare two string primitives with `===`, unlike two objects?

Strings are primitives compared by content, so two identical character sequences are ===. Two objects are only === if they're the same object, even with identical contents.

What does this log? `const a = "hi"; const b = "hi"; console.log(a === b);`

true. Strings are primitives, so the same characters mean equal values.

What's the difference between `charAt(i)`, `str[i]`, and `str.at(i)` for reading a character?

For a valid index, all three return the character. Out of range, charAt returns "", while brackets and .at() return undefined. Only .at() supports negative indexes counted from the end.

How would you check if a string is a palindrome using only built-in string and array methods?

Split into characters (str.split("")), reverse the array (.reverse()), join it back (.join("")) and compare with the original. Strings have no .reverse(), so the detour through an array is the standard approach.

What does `split(separator, limit)`'s second argument do?

It caps the number of pieces in the result. The array is cut to at most limit entries, and anything after that is dropped.

Can `split()` take a regular expression as its separator?

Yes. A regex splits on a pattern instead of a fixed substring, e.g. any run of whitespace with str.split(/\s+/).

Why is the risk with using `+` to build a dynamic string versus a template literal more than just readability?

+ chains are easy to get wrong with precedence and type coercion, e.g. numbers adding before concatenation in 1 + 1 + "1". A template literal makes each value's boundary explicit and evaluates each ${...} on its own.