JavaScript

JavaScript String Methods Cheatsheet

Quick reference for JavaScript string methods including slice, split, replace, includes, startsWith, trim, padStart, and more.

Creating Strings

const s = "hello";
const t = 'world';
const u = `Hello, ${name}!`;         // Template literal
const m = `line 1
line 2`;                              // Multiline
String(123);                          // "123"
(42).toString(16);                    // "2a" (hex)

Searching

MethodReturnsDescription
includes(str, pos?)booleanContains substring
startsWith(str, pos?)booleanStarts with substring
endsWith(str, len?)booleanEnds with substring
indexOf(str, pos?)Index or -1First occurrence
lastIndexOf(str, pos?)Index or -1Last occurrence
search(regex)Index or -1Search with regex
match(regex)Array or nullMatch against regex
matchAll(regex)IteratorAll matches (needs g flag)
"hello world".includes("world");      // true
"hello world".startsWith("hello");    // true
"hello world".indexOf("o");           // 4
"hello".search(/l+/);                 // 2
"aabba".match(/a/g);                  // ["a", "a", "a"]

Extracting

MethodReturnsDescription
slice(start, end?)StringExtract section (supports negative index)
substring(start, end?)StringExtract section (no negative index)
at(index)CharacterCharacter at index (supports negative)
charAt(index)CharacterCharacter at index
charCodeAt(index)NumberUTF-16 code unit
codePointAt(index)NumberUnicode code point
"hello world".slice(0, 5);            // "hello"
"hello world".slice(-5);              // "world"
"hello".at(-1);                       // "o"

Transforming

MethodReturnsDescription
toUpperCase()StringAll uppercase
toLowerCase()StringAll lowercase
trim()StringRemove whitespace both ends
trimStart()StringRemove leading whitespace
trimEnd()StringRemove trailing whitespace
padStart(len, fill?)StringPad start to length
padEnd(len, fill?)StringPad end to length
repeat(n)StringRepeat n times
normalize(form?)StringUnicode normalization
"  hello  ".trim();                    // "hello"
"5".padStart(3, "0");                  // "005"
"ha".repeat(3);                        // "hahaha"

Replacing

MethodReturnsDescription
replace(search, replacement)StringReplace first match
replaceAll(search, replacement)StringReplace all matches
"hello world".replace("world", "JS"); // "hello JS"
"aaa".replaceAll("a", "b");           // "bbb"
"abc 123".replace(/\d+/, "#");        // "abc #"

// With capture groups
"John Smith".replace(/(\w+) (\w+)/, "$2, $1"); // "Smith, John"

// With function
"hello".replace(/./g, c => c.toUpperCase()); // "HELLO"

Splitting & Joining

"a,b,c".split(",");                   // ["a", "b", "c"]
"a,b,c".split(",", 2);                // ["a", "b"] (limit)
"hello".split("");                     // ["h", "e", "l", "l", "o"]
["a", "b", "c"].join("-");            // "a-b-c"

Concatenating

"hello" + " " + "world";              // "hello world"
"hello".concat(" ", "world");          // "hello world"
`${a} ${b}`;                          // Template literal

Comparing

"a" < "b";                            // true (lexicographic)
"a".localeCompare("b");               // -1 (locale-aware)
"a".localeCompare("A", undefined, { sensitivity: "base" }); // 0

Raw Strings & Escape Sequences

EscapeDescription
\nNewline
\tTab
\\Backslash
\'Single quote
\"Double quote
\uXXXXUnicode character
\u{XXXXX}Unicode code point
String.raw`hello\nworld`;             // "hello\\nworld" (no escape)

Iteration

for (const char of "hello") { /* ... */ }
[..."hello"];                          // ["h", "e", "l", "l", "o"]

Common Recipes

// Capitalize first letter
s.charAt(0).toUpperCase() + s.slice(1);

// Truncate with ellipsis
s.length > n ? s.slice(0, n) + "..." : s;

// Count occurrences
(s.match(/pattern/g) || []).length;

// Remove all whitespace
s.replace(/\s/g, "");

// Slug from title
title.toLowerCase().replace(/\s+/g, "-").replace(/[^\w-]/g, "");

// Check if numeric
!isNaN(s) && !isNaN(parseFloat(s));