← All cheat sheets

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 anywhere
startsWith(sub)true if the string begins with it
endsWith(sub)true if the string ends with it
indexOf(sub)First index, or -1 if not found
lastIndexOf(sub)Last index, or -1
at(-1)Character at an index — negative counts from the end
charAt(0)Character at an index (no negatives)
search(/re/)Index of the first regex match, or -1
match(/re/)First match with capture groups, or null
matchAll(/re/g)Iterator over every match — needs the g flag

Extracting

slice(2, 5)Substring from 2 up to 5 — accepts negative indices
slice(-3)Last three characters
substring(2, 5)Like slice but clamps negatives to 0 and swaps args
split(",")Split into an array on a separator
split("")Split into characters (breaks emoji — use [...str])
split(",", 2)Stop after a set number of pieces

Transforming

toUpperCase() / toLowerCase()Change case
trim()Remove whitespace from both ends
trimStart() / trimEnd()Remove whitespace from one end
replace(a, b)Replace the first match (or all, with a /g regex)
replaceAll(a, b)Replace every occurrence of a plain string
replace(/(\w)/, (m) => ...)Pass a function to compute the replacement
repeat(3)Concatenate the string with itself n times
concat(other)Join strings — + is usually clearer
normalize("NFC")Normalise Unicode so equal-looking strings compare equal

Padding & formatting

padStart(2, "0")Pad to a length — good for times and IDs
padEnd(10, " ")Pad on the right to align columns
lengthNumber of UTF-16 code units, not visible characters
[...str].lengthCounts code points — handles emoji better
localeCompare(other)Locale-aware comparison for sorting
`a ${b} c`Template literal — interpolation and multiline
String.raw`C:\n`Keeps backslashes literal

Conversion

String(x)Convert any value to a string safely
Number("42")String to number — NaN if invalid
parseInt("42px", 10)Leading integer — always pass the radix
parseFloat("3.14rem")Leading decimal number
JSON.parse(s) / JSON.stringify(o)Between JSON text and objects
encodeURIComponent(s)Escape a value for use in a URL

JS 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.

Related guides

More cheat sheets