elefcode
← 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

More cheat sheets