JavaScript Cheatsheet

Strings

Use this JavaScript reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

String Literals

'single quotes'
"double quotes"
`template literal ${1 + 1}`      // expression interpolation
`multi
line
string`                           // actual newlines preserved

// Tagged templates
const html = String.raw`C:\Users\name\n`; // raw — no escape processing
tag`Hello ${name}, you are ${age}!`;      // custom tag function

// Escape sequences
"\n"    // newline
"\t"    // tab
"\r"    // carriage return
"\\"    // backslash
"\'"    // single quote
"\""    // double quote
"\`"    // backtick
"\0"    // null character
"A"    // unicode escape → "A"
"\u{1F600}" // unicode code point (ES6) → "😀"
"\xFF"      // hex escape

String Properties and Basics

const s = "Hello, World!";
s.length         // 13
s[0]             // "H"
s.at(0)          // "H"   (ES2022)
s.at(-1)         // "!"   (negative index)
s.charAt(0)      // "H"
s.charCodeAt(0)  // 72   (UTF-16 code unit)
s.codePointAt(0) // 72   (Unicode code point — handles astral chars)

String.fromCharCode(72, 101) // "He"
String.fromCodePoint(128512) // "😀"

// Strings are immutable — methods return new strings

Searching and Testing

const s = "Hello, World!";

s.includes("World")       // true
s.includes("world")       // false (case-sensitive)
s.startsWith("Hello")     // true
s.startsWith("World", 7)  // true  (starts at index 7)
s.endsWith("!")           // true
s.endsWith("World", 12)   // true  (consider only first 12 chars)

s.indexOf("o")            // 4   (first occurrence, or -1)
s.indexOf("o", 5)         // 8   (search from index 5)
s.lastIndexOf("o")        // 8
s.lastIndexOf("o", 7)     // 4   (search backwards from index 7)

s.search(/world/i)        // 7   (like indexOf but with regex, returns -1 if none)
s.match(/\w+/g)           // ["Hello","World"]
s.matchAll(/(\w+)/g)      // iterator of all matches with groups

Extracting Substrings

const s = "Hello, World!";

// slice(start, end) — end is exclusive, negative counts from end
s.slice(0, 5)    // "Hello"
s.slice(7)       // "World!"
s.slice(-6)      // "orld!"
s.slice(7, -1)   // "World"
s.slice(-6, -1)  // "orld"

// substring(start, end) — no negative support, swaps if start > end
s.substring(0, 5)  // "Hello"
s.substring(5, 0)  // "Hello"  (swapped)

// Prefer slice — more consistent behavior

Changing Case

"Hello World".toLowerCase()    // "hello world"
"Hello World".toUpperCase()    // "HELLO WORLD"
"résumé".toLocaleLowerCase()   // locale-aware
"istanbul".toLocaleUpperCase("tr") // "İSTANBUL"  (Turkish locale)

Trimming and Padding

"  hello  ".trim()       // "hello"
"  hello  ".trimStart()  // "hello  " (or trimLeft)
"  hello  ".trimEnd()    // "  hello" (or trimRight)

"5".padStart(3, "0")     // "005"  (pad to length 3)
"hi".padEnd(5, ".")      // "hi..."
"5".padStart(3)          // "  5"  (default pad with space)
"42".padStart(2, "0")    // "42"   (no-op if already long enough)

Replacing

const s = "hello hello";

// replace — replaces FIRST match only
s.replace("hello", "hi")          // "hi hello"
s.replace(/hello/, "hi")          // "hi hello"
s.replace(/hello/g, "hi")         // "hi hi"  (global flag)

// replaceAll (ES2021) — replaces all occurrences
s.replaceAll("hello", "hi")       // "hi hi"
s.replaceAll(/hello/g, "hi")      // "hi hi" (regex must have /g)

// Replacement patterns in the replacement string
"John Smith".replace(/(\w+) (\w+)/, "$2, $1")  // "Smith, John"
"hello".replace(/l/g, match => match.toUpperCase()) // "heLLo"

// Function as replacement
"abc".replace(/[a-z]/g, (char, offset) => {
  return char.toUpperCase() + offset;
}); // "A0B1C2"

Splitting

"a,b,c".split(",")          // ["a","b","c"]
"hello".split("")           // ["h","e","l","l","o"]
"a  b  c".split(/\s+/)     // ["a","b","c"]
"a,b,c,d".split(",", 2)     // ["a","b"]  (limit)
"hello".split()             // ["hello"]  (no sep — wrap in array)

Concatenation and Repetition

"Hello" + ", " + "World!"   // "Hello, World!"
"ha".repeat(3)              // "hahaha"
"".repeat(0)                // ""

// Template literals are usually preferred for concat
const name = "World";
`Hello, ${name}!`

Normalization and Comparison

"abc".localeCompare("abd")   // -1 (a before b)
"abc".localeCompare("abc")   // 0
"abd".localeCompare("abc")   // 1

// Locale-aware sort
["é","a","z","â"].sort((a, b) => a.localeCompare(b, "fr"));

// Unicode normalization (NFC, NFD, NFKC, NFKD)
"é".normalize("NFC")  // composed form
"é".normalize("NFD")  // decomposed form (e + combining accent)
"é" === "é" // false — same char, different encoding
"é".normalize() === "é".normalize() // true

String Method Quick Reference

MethodReturnsDescription
s.lengthnumberCharacter count
s.at(i)stringChar at index (negative ok)
s.charAt(i)stringChar at index
s.charCodeAt(i)numberUTF-16 code unit
s.codePointAt(i)numberUnicode code point
s.includes(str, pos?)booleanContains substring
s.startsWith(str, pos?)booleanStarts with
s.endsWith(str, len?)booleanEnds with
s.indexOf(str, pos?)numberFirst index or -1
s.lastIndexOf(str, pos?)numberLast index or -1
s.search(re)numberFirst regex match index or -1
s.match(re)array/nullRegex match(es)
s.matchAll(re)iteratorAll regex matches
s.slice(s?, e?)stringExtract substring
s.substring(s, e?)stringExtract (no negatives)
s.toLowerCase()stringLowercase
s.toUpperCase()stringUppercase
s.trim()stringRemove surrounding whitespace
s.trimStart()stringRemove leading whitespace
s.trimEnd()stringRemove trailing whitespace
s.padStart(len, fill?)stringPad at start
s.padEnd(len, fill?)stringPad at end
s.replace(match, repl)stringReplace first match
s.replaceAll(match, repl)stringReplace all matches
s.split(sep?, limit?)arraySplit into array
s.repeat(n)stringRepeat n times
s.normalize(form?)stringUnicode normalization
s.localeCompare(other)numberLocale-aware compare
s.concat(...strs)stringConcatenate (prefer +)

Template Literal Advanced Usage

// Multiline with indentation
const html = `
  <div>
    <p>${content}</p>
  </div>
`.trim();

// Expression interpolation
const price = `Total: $${(qty * unitPrice).toFixed(2)}`;
const msg = `${count} item${count !== 1 ? "s" : ""}`;

// Nested template
const query = `SELECT * FROM users WHERE id IN (${ids.map(id => `'${id}'`).join(",")})`;

// Tagged templates
function highlight(strings, ...values) {
  return strings.reduce((acc, str, i) =>
    acc + str + (values[i] !== undefined ? `<mark>${values[i]}</mark>` : ""),
  "");
}
const result = highlight`Hello ${name}, you have ${count} messages.`;

// String.raw — no escape processing
String.raw`C:\Users\name`  // "C:\\Users\\name" (backslash preserved)
String.raw`\n\t`           // "\\n\\t" (not newline/tab)

Common Patterns

// Reverse a string
const reverse = str => [...str].reverse().join("");
// Use spread to handle multi-byte chars correctly

// Capitalize first letter
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);

// Title case
const titleCase = str =>
  str.toLowerCase().replace(/\b\w/g, c => c.toUpperCase());

// Count occurrences of a substring
const countOccurrences = (str, sub) =>
  str.split(sub).length - 1;

// Truncate with ellipsis
const truncate = (str, n) =>
  str.length > n ? str.slice(0, n - 1) + "…" : str;

// Strip HTML tags
const stripHtml = str => str.replace(/<[^>]*>/g, "");

// Escape HTML
const escapeHtml = str => str
  .replace(/&/g, "&amp;")
  .replace(/</g, "&lt;")
  .replace(/>/g, "&gt;")
  .replace(/"/g, "&quot;")
  .replace(/'/g, "&#39;");

// Camel to kebab
const camelToKebab = str => str.replace(/([A-Z])/g, "-$1").toLowerCase();

// Kebab to camel
const kebabToCamel = str => str.replace(/-(\w)/g, (_, c) => c.toUpperCase());