Languages
JavaScript String Methods Cheat Sheet
Strings in JavaScript are immutable — every method returns a new string rather than changing the original. This reference covers the methods you use most, grouped by what they do.
Put it into practice with the matching tool.
Escape a string →Advertisement
Searching
includes(sub)true if the substring appears anywherestartsWith(sub)true if the string begins with itendsWith(sub)true if the string ends with itindexOf(sub)First index, or -1 if not foundlastIndexOf(sub)Last index, or -1at(-1)Character at an index — negative counts from the endcharAt(0)Character at an index (no negatives)search(/re/)Index of the first regex match, or -1match(/re/)First match with capture groups, or nullmatchAll(/re/g)Iterator over every match — needs the g flagExtracting
slice(2, 5)Substring from 2 up to 5 — accepts negative indicesslice(-3)Last three characterssubstring(2, 5)Like slice but clamps negatives to 0 and swaps argssplit(",")Split into an array on a separatorsplit("")Split into characters (breaks emoji — use [...str])split(",", 2)Stop after a set number of piecesTransforming
toUpperCase() / toLowerCase()Change casetrim()Remove whitespace from both endstrimStart() / trimEnd()Remove whitespace from one endreplace(a, b)Replace the first match (or all, with a /g regex)replaceAll(a, b)Replace every occurrence of a plain stringreplace(/(\w)/, (m) => ...)Pass a function to compute the replacementrepeat(3)Concatenate the string with itself n timesconcat(other)Join strings — + is usually clearernormalize("NFC")Normalise Unicode so equal-looking strings compare equalPadding & formatting
padStart(2, "0")Pad to a length — good for times and IDspadEnd(10, " ")Pad on the right to align columnslengthNumber of UTF-16 code units, not visible characters[...str].lengthCounts code points — handles emoji betterlocaleCompare(other)Locale-aware comparison for sorting`a ${b} c`Template literal — interpolation and multilineString.raw`C:\n`Keeps backslashes literalConversion
String(x)Convert any value to a string safelyNumber("42")String to number — NaN if invalidparseInt("42px", 10)Leading integer — always pass the radixparseFloat("3.14rem")Leading decimal numberJSON.parse(s) / JSON.stringify(o)Between JSON text and objectsencodeURIComponent(s)Escape a value for use in a URLJS Strings in practice
Strings are immutable
No string method changes the original string; every method returns a new one. name.toUpperCase() on its own does nothing useful — assign the result. This also means building a long string piece by piece in a loop creates many intermediate strings; for large outputs, collect parts in an array and join("") at the end, although modern engines optimise simple concatenation well.
Template literals
Backtick strings allow embedded expressions, ${user.name}, and literal line breaks, which makes them the clearest way to build messages and multi-line text. Tagged templates pass the pieces to a function, which is how libraries safely build SQL queries, HTML and styled components. Never build HTML from user input with plain template literals and innerHTML; that is a direct route to XSS. Use textContent or a templating system that escapes.
Unicode pitfalls
JavaScript strings are UTF-16, so length counts code units, not characters: "😀".length is 2, and slicing can cut an emoji in half. [...str] and Array.from(str) split by code points, which handles most emoji, and Intl.Segmenter splits by user-perceived characters, including flags and family emoji. Compare user-entered strings after normalize("NFC"), since "é" can be stored as one code point or as "e" plus a combining accent.
Comparing and searching
For sorting and case-insensitive comparison in human languages, use localeCompare or Intl.Collator rather than < and toLowerCase(), which ignore language rules. includes, startsWith and endsWith are clearer than indexOf(...) !== -1. replace with a string replaces only the first match; use replaceAll, or a regular expression with the g flag, to replace every occurrence — and remember that special characters in a string passed to new RegExp must be escaped.
Formatting for people
Intl.NumberFormat formats numbers, currencies and percentages for any locale: new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(1234.5) gives "1.234,50 €". Intl.DateTimeFormat, Intl.RelativeTimeFormat ("3 days ago") and Intl.ListFormat ("A, B, and C") handle other common cases. padStart is handy for fixed-width output such as String(n).padStart(2, "0") for two-digit minutes.

