Skip to content

JavaScript Strings

Creating, slicing, searching, and transforming text with built-in string methods.

What you'll learn

  • Creating strings with single, double, and backtick quotes
  • Core methods: length, slice, indexOf, replace, split, trim
  • Why strings are immutable and methods return new strings
  • Searching with includes, startsWith, endsWith, and localeCompare
  • Converting case and handling Unicode safely

Concept

What Is a String?

A string is an ordered sequence of characters used to represent text. In JavaScript, strings are a primitive type, which means they are immutable — once created, a string cannot be changed in place. Every method that appears to "modify" a string actually returns a brand-new string.

You can create strings with single quotes, double quotes, or backticks (template literals). Single and double quotes are interchangeable; backticks allow multiline text and interpolation.

Accessing Characters and Slicing

Strings are zero-indexed and have a length property. You can read individual characters with bracket notation or charAt(), and extract substrings with slice(), substring(), or substr() (deprecated). slice() accepts negative indices to count from the end, making it the most flexible choice.

Searching and Testing

JavaScript provides a rich set of search methods: indexOf() returns the position of a substring (or -1), includes() returns a boolean, and startsWith() / endsWith() check the boundaries. For pattern matching, match() and replace() work with regular expressions. When comparing strings for sorting, prefer localeCompare() over raw < / > so that accented characters and language-specific rules sort correctly.

Transformation Methods

Common transformations include toUpperCase(), toLowerCase(), trim() (remove surrounding whitespace), split() (break into an array), replace() (swap text), and repeat() (duplicate the string). Because strings are immutable, remember to assign the result — calling str.trim() without capturing the return value does nothing to str.

Example

              const sentence = "  The quick brown fox  ";

// trim removes leading/trailing whitespace — remember to capture the result
const clean = sentence.trim();
console.log(clean); // "The quick brown fox"

// slice with negative index counts from the end
const lastWord = clean.slice(-3);
console.log(lastWord); // "fox"

// split into words, then map to lengths
const words = clean.split(" ");
const lengths = words.map((w) => w.length);
console.log(lengths); // [3, 5, 5, 3]

// search and replace
const hasFox = clean.includes("fox");
const noFox = clean.replace("fox", "cat");
console.log(hasFox, noFox); // true "The quick brown cat"

// locale-aware comparison for correct sorting
const names = ["Élodie", "Ada", "Zara"];
names.sort((a, b) => a.localeCompare(b));
console.log(names);
            

Demonstrates immutability (trim returns a new string), slicing with negative indices, splitting and mapping, searching with includes, replacing text, and locale-aware sorting.

Try it

  • Case Converter

    Convert text between camelCase, snake_case, and more — pure string methods.

  • Slugify

    Turn strings into URL-safe slugs using trim, replace, and lowercasing.

  • Text Counter

    Count characters and words — built on length and split.

Common mistakes

The mistake

Calling a string method without capturing the return value

The fix

Strings are immutable. str.trim() does not change str — you must write str = str.trim() or const clean = str.trim() to use the result.

The mistake

Using == to compare strings and getting surprised by type coercion

The fix

Always use === for string comparison. '5' === 5 is false, but '5' == 5 is true due to coercion. For sorting, use localeCompare().

Related Cheatsheets

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors