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
| API | Notes |
|---|---|
'...', "...", `tmpl $\{x\}` | Prefer templates for interpolation |
String(x), String.raw…`` | Coerce; raw skips escape processing |
str.length | UTF-16 code units |
str[i], str.at(i), str.charAt(i) | at supports negatives |
charCodeAt / codePointAt | Unit vs full code point |
Search / match
| Method | Notes |
|---|---|
includes(sub, from?) | Boolean substring |
indexOf / lastIndexOf | Index or -1 |
startsWith / endsWith | Prefix / 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
| Method | Notes |
|---|---|
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
| Method | Notes |
|---|---|
toLowerCase / toUpperCase | Locale-insensitive |
toLocaleLowerCase / …UpperCase | Locale-aware |
trim / trimStart / trimEnd | Whitespace (Unicode) |
padStart(n, fill?) / padEnd | Pad to length n |
repeat(n) | Concatenate n times |
Replace / normalize / unicode
| Method | Notes |
|---|---|
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 str | Iterates 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("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """);
}⚠️ Pitfalls
- Strings are immutable — methods return new strings.
replacewith string pattern replaces only the first match — usereplaceAllor/g.- Surrogate pairs:
"🙂".length === 2; preferfor...of/codePointAt. ==coerces; compare with===.- Building HTML via concatenation risks XSS — escape or use DOM APIs / frameworks.
🔗 Related
- encode.md — URI encoding
- boolean.md — empty string falsy
- arrays.md — split/join
- json.md — string escaping
- for_of.md — iterating characters
- DOM/content_methods.md — text vs HTML