Code Reference

Strings

JavaScript · Reference cheat sheet

Strings

JavaScript · Reference cheat sheet

📋 Overview

Strings are immutable UTF-16 sequences. Prefer template literals, includes/startsWith, and replaceAll over older index loops. For full Unicode graphemes, be aware of code units vs code points.

🔧 Core concepts

Create / access

APINotes
'...', "...", `tmpl $\{x\}`Prefer templates for interpolation
String(x), String.raw…``Coerce; raw skips escape processing
str.lengthUTF-16 code units
str[i], str.at(i), str.charAt(i)at supports negatives
charCodeAt / codePointAtUnit vs full code point

Search / match

MethodNotes
includes(sub, from?)Boolean substring
indexOf / lastIndexOfIndex or -1
startsWith / endsWithPrefix / suffix (pos optional)
search(re)First regex match index
match(re)Match array or null
matchAll(re)Iterator of all matches (/g required)

Slice / split / join

MethodNotes
slice(start?, end?)Supports negatives; preferred
substring(a, b)Swaps if a > b; no negatives
substr(start, len)Legacy — avoid
split(sep|re, limit?)→ array; empty sep → chars
Array .join(sep)Inverse of split

Case / trim / pad / repeat

MethodNotes
toLowerCase / toUpperCaseLocale-insensitive
toLocaleLowerCase / …UpperCaseLocale-aware
trim / trimStart / trimEndWhitespace (Unicode)
padStart(n, fill?) / padEndPad to length n
repeat(n)Concatenate n times

Replace / normalize / unicode

MethodNotes
replace(pat, rep|fn)First match only if string//g missing
replaceAll(pat, rep|fn)All; string or global regex
normalize("NFC"|"NFD"|…)Unicode normalization forms
localeCompare(other, locales?, opts?)Collation compare → −1/0/1
for...of strIterates code points
[...str] / Array.from(str)Code-point array
const name = "Ada";
`Hello, ${name}!`;
"file.js".endsWith(".js"); // true

💡 Examples

const s = "  Hello, World  ";
s.trim().toLowerCase(); // "hello, world"
"a-b-c".split("-"); // ["a","b","c"]
"na".repeat(3); // "nanana"
"id".padStart(4, "0"); // "00id"
"foo bar foo".replaceAll("foo", "baz");

// Template multiline
const html = `
  <div class="card">
    ${title}
  </div>
`.trim();

// Code points iteration
for (const ch of "A🙂B") console.log(ch);

// matchAll
const re = /\d+/g;
for (const m of "a1 b23".matchAll(re)) {
  console.log(m[0], m.index);
}

// Slice vs substring
"abcdef".slice(1, -1); // "bcde"
"abcdef".substring(1, 4); // "bcd"

// Normalize Unicode
"é".normalize("NFC");
// Safe HTML escape (minimal)
function escapeHtml(str) {
  return str
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;");
}

⚠️ Pitfalls

  • Strings are immutable — methods return new strings.
  • replace with string pattern replaces only the first match — use replaceAll or /g.
  • Surrogate pairs: "🙂".length === 2; prefer for...of / codePointAt.
  • == coerces; compare with ===.
  • Building HTML via concatenation risks XSS — escape or use DOM APIs / frameworks.

On this page