JavaScript String Methods: Every Method Explained with Examples
The complete reference for JavaScript string methods. Every method explained with clear examples — from basics like slice and split to modern methods like replaceAll and at.
DevToolsHub Team20 min read879 words
String Basics
Strings in JavaScript are immutable sequences of characters. Every string method returns a new string — the original is never modified.
const str = "Hello, World!";
str.toUpperCase(); // "HELLO, WORLD!"
console.log(str); // "Hello, World!" — unchanged
Finding and Searching
indexOf / lastIndexOf
const str = "Hello World Hello";
str.indexOf("Hello"); // 0 (first occurrence)
str.indexOf("Hello", 1); // 12 (search from index 1)
str.indexOf("xyz"); // -1 (not found)
str.lastIndexOf("Hello"); // 12 (last occurrence)
includes / startsWith / endsWith
const str = "Hello, World!";
str.includes("World"); // true
str.includes("world"); // false (case-sensitive)
str.startsWith("Hello"); // true
str.startsWith("World", 7); // true (from position 7)
str.endsWith("!"); // true
str.endsWith("World", 12); // true (check first 12 chars)
search (with regex)
const str = "The price is $42.99";
str.search(/\d+/); // 14 (index of first digit)
str.search(/xyz/); // -1 (not found)
match / matchAll
const str = "Call 555-1234 or 555-5678";
// match — returns first match (without g flag)
str.match(/\d{3}-\d{4}/);
// ["555-1234", index: 5, ...]
// match — returns all matches (with g flag)
str.match(/\d{3}-\d{4}/g);
// ["555-1234", "555-5678"]
// matchAll — returns iterator with details
[...str.matchAll(/(\d{3})-(\d{4})/g)].forEach(m => {
console.log(m[0], m[1], m[2]); // full match, group 1, group 2
});
Test your regex patterns with our Regex Tester tool.
Extracting Substrings
slice
The most versatile extraction method:
const str = "Hello, World!";
str.slice(7); // "World!"
str.slice(7, 12); // "World"
str.slice(-6); // "orld!"
str.slice(-6, -1); // "orld"
str.slice(0, 5); // "Hello"
substring
Similar to slice but doesn't support negative indices:
str.substring(7, 12); // "World"
str.substring(7); // "World!"
at (ES2022)
Access characters by index, supports negative:
str.at(0); // "H"
str.at(-1); // "!"
str.at(-2); // "d"
Transforming
toUpperCase / toLowerCase
"hello".toUpperCase(); // "HELLO"
"HELLO".toLowerCase(); // "hello"
trim / trimStart / trimEnd
" hello ".trim(); // "hello"
" hello ".trimStart(); // "hello "
" hello ".trimEnd(); // " hello"
padStart / padEnd
"5".padStart(3, "0"); // "005"
"42".padStart(5, " "); // " 42"
"hi".padEnd(10, "."); // "hi........"
// Common use: format numbers
const price = 9.99;
String(price).padStart(8, " "); // " 9.99"
repeat
"ha".repeat(3); // "hahaha"
"-".repeat(40); // "----------------------------------------"
"abc".repeat(0); // ""
replace / replaceAll
const str = "Hello World Hello";
// replace — first occurrence only
str.replace("Hello", "Hi"); // "Hi World Hello"
// replace with regex (g flag for all)
str.replace(/Hello/g, "Hi"); // "Hi World Hi"
// replaceAll (ES2021) — all occurrences
str.replaceAll("Hello", "Hi"); // "Hi World Hi"
// replace with function
"hello world".replace(/\b\w/g, c => c.toUpperCase());
// "Hello World"
Splitting and Joining
split
"a,b,c".split(","); // ["a", "b", "c"]
"hello world".split(" "); // ["hello", "world"]
"hello".split(""); // ["h", "e", "l", "l", "o"]
"a,b,c,d".split(",", 2); // ["a", "b"] (limit)
// Split by regex
"one1two2three".split(/\d/); // ["one", "two", "three"]
Array.join (the reverse of split)
["a", "b", "c"].join(", "); // "a, b, c"
["a", "b", "c"].join("-"); // "a-b-c"
["a", "b", "c"].join(""); // "abc"
Template Literals
const name = "Alice";
const age = 30;
// String interpolation
`Hello, ${name}! You are ${age} years old.`
// Multi-line strings
`Line 1
Line 2
Line 3`
// Expressions
`Total: $${(price * quantity).toFixed(2)}`
// Tagged templates
function highlight(strings, ...values) {
return strings.reduce((result, str, i) =>
result + str + (values[i] ? `<mark>${values[i]}</mark>` : ""), "");
}
highlight`Hello ${name}, you are ${age}!`
// "Hello <mark>Alice</mark>, you are <mark>30</mark>!"
Common Patterns
Capitalize first letter
const capitalize = s => s.charAt(0).toUpperCase() + s.slice(1);
capitalize("hello"); // "Hello"
Title case
const titleCase = s => s.replace(/\b\w/g, c => c.toUpperCase());
titleCase("hello world"); // "Hello World"
Truncate with ellipsis
const truncate = (s, max) =>
s.length > max ? s.slice(0, max - 3) + "..." : s;
truncate("Hello, World!", 10); // "Hello, ..."
Slug from text
const slugify = s => s
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-|-$/g, "");
slugify("Hello World! 2024"); // "hello-world-2024"
Generate slugs with our Text to Slug converter.
Count occurrences
const count = (str, sub) =>
(str.match(new RegExp(sub, "gi")) || []).length;
count("Hello World Hello", "Hello"); // 2
Count words and characters with our Word Counter tool.
Quick Reference
| Method | Returns | Mutates? |
|---|---|---|
indexOf() | Number | No |
includes() | Boolean | No |
slice() | String | No |
split() | Array | No |
replace() | String | No |
replaceAll() | String | No |
toUpperCase() | String | No |
toLowerCase() | String | No |
trim() | String | No |
padStart() | String | No |
repeat() | String | No |
match() | Array/null | No |
search() | Number | No |
at() | String | No |
Related Tools
- Regex Tester — Test regex patterns with match highlighting
- Word Counter — Count words, characters, sentences
- Case Converter — Convert between text cases
- Text to Slug — Generate URL-friendly slugs
- String Escape/Unescape — Escape strings for JSON, JS, HTML
- Text Diff Checker — Compare two texts
- Base64 Encoder — Encode/decode strings
javascript stringsstring methodsjavascript stringslicesplitreplaceincludesjs string methods