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 URL