JavaScript String Methods Cheat Sheet
Quick-reference for every string method you actually use. Each section includes copy-ready snippets with inline output comments.
split() and join()
split() turns a string into an array. join() turns an array into a string. They are inverse operations.
'a,b,c'.split(',') // => ['a', 'b', 'c']
'hello world'.split(' ') // => ['hello', 'world']'a:b:c:d'.split(':', 2) // => ['a', 'b']'hello'.split('') // => ['h', 'e', 'l', 'l', 'o']
[...'hello'] // => ['h', 'e', 'l', 'l', 'o'] (spread also works)['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.
'hello world'.includes('world') // => true
'hello world'.includes('xyz') // => false
'hello world'.includes('Hello') // => false (case-sensitive)'hello.js'.startsWith('hello') // => true
'hello.js'.endsWith('.js') // => true
'hello.js'.endsWith('.ts') // => false'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.
' hello world '.trim() // => 'hello world'
'\t\nhello\n\t'.trim() // => 'hello'' hello '.trimStart() // => 'hello '
' hello '.trimEnd() // => ' hello'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.
'5'.padStart(3, '0') // => '005'
'42'.padStart(5, '0') // => '00042'
'123'.padStart(3, '0') // => '123' (already 3+ chars)'hi'.padEnd(10, '.') // => 'hi........'
'hello'.padEnd(10, ' ') // => 'hello '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.
'ha'.repeat(3) // => 'hahaha'
'-'.repeat(20) // => '--------------------'
'abc'.repeat(0) // => ''const divider = '='.repeat(40);
console.log(divider);
// => '========================================'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.
'a_b_c'.replace('_', '-') // => 'a-b_c' (first only!)
'hello'.replace('l', 'L') // => 'heLlo''a_b_c'.replaceAll('_', '-') // => 'a-b-c'
'hello'.replaceAll('l', 'L') // => 'heLLo''hello123world'.replace(/\d+/, '#') // => 'hello#world'
'hello123world456'.replace(/\d+/g, '#') // => 'hello#world#'// 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.
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'const msg = `Line one
Line two
Line three`;
msg.split('\n').length // => 3function 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><script>alert(1)</script></div>'Tag functions receive string parts and interpolated values separately. They do NOT auto-escape — your tag must implement sanitization.
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.
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 // => 3const 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/15const text = 'aaa bbb';
text.match(/\w+/g) // => ['aaa', 'bbb'] (no groups)
[...text.matchAll(/\w+/g)] // => full match objects with index, groupsmatch() 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.
'hello'.at(0) // => 'h'
'hello'.at(-1) // => 'o' (last)
'hello'.at(-2) // => 'l'const str = 'hello';
str[str.length - 1] // => 'o' (old way)
str.at(-1) // => 'o' (cleaner)
str[-1] // => undefined (brackets don't support negative)function endsWithPunctuation(str) {
return '.!?'.includes(str.at(-1));
}
endsWithPunctuation('Hello!') // => true
endsWithPunctuation('Hello') // => falseslice() vs substring()
Both extract substrings, but they handle edge cases differently. Prefer slice() — it supports negative indices and matches array behavior.
'JavaScript'.slice(0, 4) // => 'Java'
'JavaScript'.slice(4) // => 'Script'
'JavaScript'.slice(-6) // => 'Script' (from end)
'JavaScript'.slice(-6, -3) // => 'Scr''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().
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.
'hello'.toUpperCase() // => 'HELLO'
'HELLO'.toLowerCase() // => 'hello''i'.toLocaleUpperCase('tr') // => 'İ' (Turkish dotted I)
'I'.toLocaleLowerCase('tr') // => 'ı' (Turkish dotless i)'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.
Can you write this from memory?
Check if string `item_text` matches the pattern `/abc/`.