JavaScript String Methods Reference
All 31 String methods — signature, parameter table, return value, ES badge, and examples — browse, search, or quick-lookup any method
Browse by Category
You need to check if a string starts with “https://” — is it startsWith() or indexOf() === 0? You need to replace all occurrences of a substring — replace() only does the first match, you need replaceAll() (or replace() with /g). You need to pad a number to 3 digits — padStart(3, '0'), but you always forget which argument is the pad string and which is the target length. String has 30+ methods and the naming isn’t always intuitive.
Why This Reference (Not MDN)
MDN documents each String method on a separate page. This reference puts all methods on one page organized by category — Search, Extract, Transform, Split/Join, and Compare — with syntax, return types, and example code. Searchable and filterable. Find the right method by what you need to do, not by name.
What This Reference Covers
JavaScript strings come with a comprehensive set of built-in methods for searching, extracting substrings, transforming case and whitespace, splitting and joining, and locale-aware comparison. This interactive reference covers all 28 String.prototype methods organized into five functional categories.
Every entry shows:
- Syntax — the exact call signature with parameter names
- Return type — what the method produces
- Description — what the method does and when to use it
- Code example — a runnable, copy-pasteable example
Use the search box to find a method by name, keyword, or return type. Use the category tabs to focus on a specific area.
The Five Categories
Search Methods
Search methods tell you whether a pattern exists in a string and where to find it.
| Method | Returns | Use case |
|---|---|---|
indexOf | number | First index of substring, or -1 |
lastIndexOf | number | Last index of substring, or -1 |
search | number | First index of regex match, or -1 |
includes | boolean | Does the string contain searchString? |
startsWith | boolean | Does the string start with searchString? |
endsWith | boolean | Does the string end with searchString? |
match | Array | null | First match (or all matches with /g) |
matchAll | Iterator | All matches with capture groups and positions |
When to use each:
includes— simple existence check, cleaner thanindexOf !== -1startsWith/endsWith— protocol/extension checks, cleaner thanslicecomparisonsindexOf/lastIndexOf— when you need the position, not just existencematch— extract data from a pattern (e.g., parse version numbers)matchAll— extract all matches with groups and positions (e.g., parse all URLs in a document)
Extract Methods
Extract methods return a portion of the string without modifying the original.
| Method | Negative index? | Out-of-range |
|---|---|---|
charAt(i) | No (returns ”) | Returns ” |
charCodeAt(i) | No | Returns NaN |
codePointAt(i) | No | Returns undefined |
slice(start, end?) | Yes | Clamped to bounds |
substring(start, end?) | No (treated as 0) | Clamped to bounds |
at(i) | Yes | Returns undefined |
slice vs substring:
slice is generally preferred because it handles negative indices predictably — negative values count backwards from the end. substring treats negative values as 0 and swaps arguments when start > end, which can lead to surprising behavior.
const str = 'Hello World';
str.slice(-5); // 'World' (last 5 chars)
str.substring(-5); // 'Hello World' (treated as 0)
charAt vs bracket notation:
const str = 'hello';
str.charAt(10); // '' (empty string for out-of-range)
str[10]; // undefined (differs from charAt)
Use at() for the cleanest negative-index access:
'hello'.at(-1); // 'o' — last character, no math needed
Transform Methods
Transform methods return a new string with modifications applied — strings are immutable in JavaScript, so the original is never changed.
Case conversion:
'Hello World'.toUpperCase(); // 'HELLO WORLD'
'Hello World'.toLowerCase(); // 'hello world'
Whitespace removal:
' hello '.trim(); // 'hello'
' hello '.trimStart(); // 'hello '
' hello '.trimEnd(); // ' hello'
Padding — useful for formatting:
'7'.padStart(2, '0'); // '07' — zero-pad numbers
'7'.padEnd(3, '.'); // '7..' — right-align text
Repetition:
'=-'.repeat(20); // '=-=-=-=-=-=-=-=-=-=-'
Replacement:
// replace() — first match only (with a string searchFor)
'a-b-c'.replace('-', ''); // 'ab-c' (only first!)
// replaceAll() — all occurrences
'a-b-c'.replaceAll('-', ''); // 'abc' (all!)
Split / Join Methods
split converts a string to an array of substrings by a separator. It is the inverse of Array.prototype.join.
// String → Array
'a,b,c'.split(','); // ['a', 'b', 'c']
// Array → String
['a', 'b', 'c'].join(','); // 'a,b,c'
concat joins multiple strings, though template literals are almost always preferred:
// Avoid:
'Hello'.concat(' ').concat('World');
// Prefer:
`Hello World`
Compare Methods
localeCompare provides linguistically correct string comparison, handling accented characters, locale-specific rules, and configurable case sensitivity.
// Naive sort breaks on accented characters:
['Zebra', 'ångström', 'Apple'].sort();
// ['Apple', 'Zebra', 'ångström'] (wrong — ångström should come before Apple)
// localeCompare sorts correctly:
['Zebra', 'ångström', 'Apple'].sort((a, b) => a.localeCompare(b));
// ['ångström', 'Apple', 'Zebra'] (correct)
Key Patterns
Case-Insensitive Search
// startsWith/endsWith don't have a case-insensitive option
// — normalize first:
const url = 'HTTPS://example.com';
url.toLowerCase().startsWith('https://'); // true
// search() and match() accept case-insensitive flags:
'Hello World'.search(/hello/i); // 0
Extract After the Last Occurrence
const path = '/usr/local/bin/node';
const filename = path.slice(path.lastIndexOf('/') + 1);
// 'node'
Check Multiple Extensions
const ext = filename.slice(filename.lastIndexOf('.'));
const imageExts = ['.png', '.jpg', '.gif', '.webp', '.svg'];
const isImage = imageExts.includes(ext.toLowerCase());
Safe Unicode Handling
For strings that may contain emoji or other non-BMP characters, use codePointAt and spread iteration:
// Correctly counts characters including emoji
const chars = [...'Hello 😀'];
chars.length; // 7 (not 8)
chars[6]; // '😀'
Build a Slug from a Title
function slugify(title) {
return title
.toLowerCase()
.normalize('NFD') // decompose accents
.replace(/[\u0300-\u036f]/g, '') // strip combining marks
.trim()
.replaceAll(/\s+/g, '-') // spaces to dashes
.replace(/[^a-z0-9-]/g, ''); // remove special chars
}
slugify('Héllo Wörld!'); // 'hello-world'
Browser Support
All methods in this reference are supported in all modern browsers and Node.js.
| Method | ES Version | Notes |
|---|---|---|
indexOf, charAt, charCodeAt, slice, substring, concat, split, toUpperCase, toLowerCase | ES1/ES3 | Universal support |
trim | ES5 | IE9+ |
search, match, replace | ES3 | Universal |
startsWith, endsWith, includes, repeat, codePointAt, normalize | ES2015 | IE not supported |
padStart, padEnd | ES2017 | IE not supported |
trimStart, trimEnd | ES2019 | Modern browsers |
matchAll, replaceAll | ES2021 | Chrome 73+, Firefox 77+, Safari 13.1+ |
at | ES2022 | Chrome 92+, Firefox 90+, Safari 15.4+ |
FAQ
What is the difference between slice and substring?
The key differences: slice supports negative indices (counting from the end), while substring treats negative values as 0. If start > end, substring swaps the arguments; slice returns an empty string. Prefer slice for its predictable behavior with negative values.
When should I use includes instead of indexOf?
Use includes when you only need to know whether a string contains another string. It returns a boolean and communicates intent clearly. Use indexOf when you also need the position. includes was introduced in ES2015; for legacy environments use indexOf(str) !== -1.
What is the difference between match and matchAll?
match without /g returns the first match with capture groups. match with /g returns all matched substrings but without capture groups or index positions. matchAll (ES2021) always returns an iterator where each entry includes capture groups and the index — useful when you need both all matches and their details.
Why use codePointAt instead of charCodeAt?
charCodeAt returns UTF-16 code units (0–65535). Characters outside the Basic Multilingual Plane — like emoji — are stored as surrogate pairs (two code units), so charCodeAt(0) on an emoji returns the first surrogate half, not the character’s actual code point. codePointAt reconstructs the full code point correctly.
What does normalize do and when is it needed?
Accented characters like é can be represented in Unicode in two ways: as a single precomposed character (U+00E9) or as a base character + combining accent mark (U+0065 + U+0301). These look identical but are different byte sequences, causing string equality to fail. Calling .normalize('NFC') converts to the single precomposed form, making comparison reliable.
When should I use localeCompare for sorting?
Always use localeCompare when sorting strings that users will see — especially when the data may contain accented characters, special characters like ß, or when you want case-insensitive sorting. localeCompare understands language rules that a simple < / > comparison ignores.
All processing happens in your browser. No text is sent to any server.