JavaScript strings are immutable UTF-16 sequences. Methods like slice, split, trim, and replaceAll return new strings. Template literals interpolate values and multi-line text. Do not use length as a character count when emoji or combining marks matter — use Intl.Segmenter or [...str].
This JavaScript cheat sheet is written for people searching for a fast, accurate reference: students, junior developers, and teams shipping production software. Pin it, copy the snippets, and come back when syntax slips.
Quick reference
- slice:
str.slice(0, 8)copy. Negative indexes count from the end. - split / join:
csv.split(",")andparts.join(" · "). - trim:
trim,trimStart,trimEndfor form input. - search:
includes,startsWith,endsWith— case-sensitive. Normalize withtoLowerCase. - replace:
replacechanges one match unless you pass/g.replaceAllneeds a string or global regex. - pad:
padStart(2, "0")for clocks and invoice numbers. - template: `
Hello ${name}`. Escape user HTML before inserting into the DOM. - Number:
Number.parseInt(str, 10)andNumber(str)— watch empty string → 0.
Copy-paste examples
Slug and display helpers
Normalize once, then compare. replaceAll is clearer than /g for literal separators.
function slugify(title) {
return title
.trim()
.toLowerCase()
.replaceAll(' ', '-')
.replaceAll(/[^a-z0-9-]/g, '');
}
function initials(name) {
return name
.trim()
.split(/\s+/)
.map((p) => p[0])
.join('')
.toUpperCase();
}Common mistakes
- Mutating thinking:
str.replacedoes nothing unless you assign the return value. parseInt("08")without radix in old engines; always pass10.- Building HTML with template literals from user input (XSS).
- Using
split("")on emoji strings and breaking characters.
FAQ
- String vs String object? Prefer primitives
"hi".new String()boxes and fails some===checks. You almost never need the constructor.