Syntax Cache
BlogMethodFeaturesHow It WorksBuild a Game
  1. Home
  2. Cheat Sheets
  3. JavaScript
  4. JavaScript String Methods Cheat Sheet
JavaScriptCheat Sheet

JavaScript String Methods Cheat Sheet

Quick-reference for every string method you actually use. Each section includes copy-ready snippets with inline output comments.

On this page
  1. 1split() and join()
  2. 2includes(), startsWith(), endsWith()
  3. 3trim(), trimStart(), trimEnd()
  4. 4padStart() and padEnd()
  5. 5repeat()
  6. 6replace() and replaceAll()
  7. 7Template Literals and Tagged Templates
  8. 8matchAll()
  9. 9at() — Negative Indexing
  10. 10slice() vs substring()
  11. 11Case and Locale Methods
split() and join()includes(), startsWith(), endsWith()trim(), trimStart(), trimEnd()padStart() and padEnd()repeat()replace() and replaceAll()Template Literals and Tagged TemplatesmatchAll()at() — Negative Indexingslice() vs substring()Case and Locale Methods

split() and join()

split() turns a string into an array. join() turns an array into a string. They are inverse operations.

Split on delimiter
'a,b,c'.split(',')     // => ['a', 'b', 'c']
'hello world'.split(' ')  // => ['hello', 'world']
Split with limit
'a:b:c:d'.split(':', 2)  // => ['a', 'b']
Split into characters
'hello'.split('')  // => ['h', 'e', 'l', 'l', 'o']
[...'hello']       // => ['h', 'e', 'l', 'l', 'o'] (spread also works)
join() — array to string
['hello', 'world'].join(' ')   // => 'hello world'
['2026', '02', '22'].join('-')  // => '2026-02-22'
[1, 2, 3].join(', ')           // => '1, 2, 3'

includes(), startsWith(), endsWith()

Boolean checks for substring presence and position. Cleaner than indexOf() !== -1.

includes() — substring exists
'hello world'.includes('world')  // => true
'hello world'.includes('xyz')    // => false
'hello world'.includes('Hello')  // => false (case-sensitive)
startsWith() and endsWith()
'hello.js'.startsWith('hello')   // => true
'hello.js'.endsWith('.js')       // => true
'hello.js'.endsWith('.ts')       // => false
Optional position parameter
'hello world'.includes('world', 6)     // => true (search from index 6)
'hello world'.startsWith('world', 6)   // => true
'hello world'.endsWith('hello', 5)     // => true (treat first 5 chars as string)

trim(), trimStart(), trimEnd()

Remove whitespace from string boundaries. Does not modify interior whitespace.

trim() — both sides
'  hello world  '.trim()       // => 'hello world'
'\t\nhello\n\t'.trim()          // => 'hello'
trimStart() and trimEnd()
'  hello  '.trimStart()  // => 'hello  '
'  hello  '.trimEnd()    // => '  hello'
Common pattern: clean user input
const email = userInput.trim().toLowerCase();
if (!email.includes('@')) {
  throw new Error('Invalid email');
}

padStart() and padEnd()

Pad strings to a target length with a fill character. Useful for alignment and formatting.

Zero-padding numbers
'5'.padStart(3, '0')     // => '005'
'42'.padStart(5, '0')    // => '00042'
'123'.padStart(3, '0')   // => '123' (already 3+ chars)
Right-padding for alignment
'hi'.padEnd(10, '.')      // => 'hi........'
'hello'.padEnd(10, ' ')   // => 'hello     '
Format time components
const h = String(hours).padStart(2, '0');
const m = String(minutes).padStart(2, '0');
const time = `${h}:${m}`;  // => '09:05'

repeat()

Create a string by repeating it a given number of times.

Basic repetition
'ha'.repeat(3)     // => 'hahaha'
'-'.repeat(20)     // => '--------------------'
'abc'.repeat(0)    // => ''
Build visual separators
const divider = '='.repeat(40);
console.log(divider);
// => '========================================'
Indent text
function indent(text, level) {
  return ' '.repeat(level * 2) + text;
}
indent('hello', 3)  // => '      hello'

replace() and replaceAll()

replace() hits the first match only (with string patterns). replaceAll() hits every match.

replace() — first match only
'a_b_c'.replace('_', '-')   // => 'a-b_c' (first only!)
'hello'.replace('l', 'L')   // => 'heLlo'
replaceAll() — all matches
'a_b_c'.replaceAll('_', '-')  // => 'a-b-c'
'hello'.replaceAll('l', 'L')  // => 'heLLo'
Regex with replace
'hello123world'.replace(/\d+/, '#')   // => 'hello#world'
'hello123world456'.replace(/\d+/g, '#')  // => 'hello#world#'
replaceAll with regex requires /g flag
// TypeError! Missing /g flag
// 'abc'.replaceAll(/a/, 'x')

// Correct:
'abc'.replaceAll(/a/g, 'x')  // => 'xbc'

replaceAll() throws TypeError if you pass a regex without the global (/g) flag.

Template Literals and Tagged Templates

Backtick strings support expression interpolation, multiline text, and tagged template processing.

Interpolation
const name = 'Alice';
`Hello, ${name}!`               // => 'Hello, Alice!'
`Total: $${(9.99 * 3).toFixed(2)}`  // => 'Total: $29.97'
`${2 + 2} is ${2 + 2 === 4 ? 'correct' : 'wrong'}`
// => '4 is correct'
Multiline
const msg = `Line one
Line two
Line three`;
msg.split('\n').length  // => 3
Tagged templates
function html(strings, ...values) {
  return strings.reduce((acc, str, i) => {
    const val = values[i] !== undefined ? escapeHtml(values[i]) : '';
    return acc + str + val;
  }, '');
}

const input = '<script>alert(1)</script>';
html`<div>${input}</div>`
// => '<div>&lt;script&gt;alert(1)&lt;/script&gt;</div>'

Tag functions receive string parts and interpolated values separately. They do NOT auto-escape — your tag must implement sanitization.

String.raw — no escape processing
String.raw`\n\t`           // => '\\n\\t' (literal backslashes)
String.raw`C:\Users\docs`   // => 'C:\\Users\\docs'

matchAll()

Return an iterator of all regex matches with capture groups. Requires the /g flag.

Basic matchAll
const text = 'price: $10, tax: $2, total: $12';
const matches = [...text.matchAll(/\$(\d+)/g)];

matches[0][0]  // => '$10' (full match)
matches[0][1]  // => '10'  (capture group)
matches.length // => 3
Extract named groups
const dates = '2026-02-22, 2026-03-15';
const pattern = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/g;

for (const match of dates.matchAll(pattern)) {
  const { year, month, day } = match.groups;
  console.log(`${year}/${month}/${day}`);
}
// 2026/02/22
// 2026/03/15
matchAll vs match
const text = 'aaa bbb';
text.match(/\w+/g)      // => ['aaa', 'bbb'] (no groups)
[...text.matchAll(/\w+/g)]  // => full match objects with index, groups

match() with /g returns only matched strings. matchAll() returns full match objects including capture groups and indices.

at() — Negative Indexing

The at() method (ES2022) supports negative indices for accessing characters from the end of a string.

Positive and negative indices
'hello'.at(0)    // => 'h'
'hello'.at(-1)   // => 'o' (last)
'hello'.at(-2)   // => 'l'
vs bracket notation
const str = 'hello';
str[str.length - 1]  // => 'o' (old way)
str.at(-1)           // => 'o' (cleaner)

str[-1]              // => undefined (brackets don't support negative)
Check last character
function endsWithPunctuation(str) {
  return '.!?'.includes(str.at(-1));
}
endsWithPunctuation('Hello!')  // => true
endsWithPunctuation('Hello')   // => false

slice() vs substring()

Both extract substrings, but they handle edge cases differently. Prefer slice() — it supports negative indices and matches array behavior.

slice() — supports negative indices
'JavaScript'.slice(0, 4)   // => 'Java'
'JavaScript'.slice(4)      // => 'Script'
'JavaScript'.slice(-6)     // => 'Script' (from end)
'JavaScript'.slice(-6, -3) // => 'Scr'
substring() — clamps negatives to 0
'JavaScript'.substring(0, 4)  // => 'Java' (same)
'JavaScript'.substring(-6)   // => 'JavaScript' (negative -> 0)
'JavaScript'.substring(4, 0) // => 'Java' (swaps args!)

slice() treats negatives as from-end offsets. substring() clamps negatives to 0 and swaps reversed arguments. Prefer slice().

Extract file extension
const filename = 'report.final.pdf';
filename.slice(filename.lastIndexOf('.'))  // => '.pdf'
filename.slice(0, filename.lastIndexOf('.'))  // => 'report.final'

Case and Locale Methods

Convert case and compare strings with locale awareness.

toUpperCase() and toLowerCase()
'hello'.toUpperCase()  // => 'HELLO'
'HELLO'.toLowerCase()  // => 'hello'
Locale-aware case (Turkish i)
'i'.toLocaleUpperCase('tr')  // => 'İ' (Turkish dotted I)
'I'.toLocaleLowerCase('tr')  // => 'ı' (Turkish dotless i)
localeCompare for sorting
'a'.localeCompare('b')          // => -1 (a before b)
'ä'.localeCompare('z', 'de')     // => -1 (ä before z in German)
'ä'.localeCompare('z', 'sv')     // => 1  (ä after z in Swedish)

For sorting arrays of strings, use localeCompare or Intl.Collator for locale-correct ordering.

Learn JavaScript in Depth
JavaScript Collections Practice →JavaScript Functions Practice →
Warm-up1 / 2

Can you write this from memory?

Check if string `item_text` matches the pattern `/abc/`.

See Also
Array Methods →DOM Manipulation →

Start Practicing JavaScript

Free daily exercises with spaced repetition. No credit card required.

← Back to JavaScript Syntax Practice
Syntax Cache

Build syntax muscle memory with spaced repetition.

Product

  • Pricing
  • Our Method
  • Daily Practice
  • Design Patterns
  • Interview Prep

Resources

  • Blog
  • Compare
  • Cheat Sheets
  • Vibe Coding
  • Muscle Memory

Languages

  • Python
  • JavaScript
  • TypeScript
  • Rust
  • SQL
  • GDScript

Legal

  • Terms
  • Privacy
  • Contact

© 2026 Syntax Cache

Cancel anytime in 2 clicks. Keep access until the end of your billing period.

No refunds for partial billing periods.