JavaScript String Methods: Searching, Slicing, Replacing, Padding and More
A practical tour of the string API with runnable examples: slice vs substring vs substr, indexOf and includes, replace vs replaceAll and the $ patterns, split edge cases, trimming, padding, case conversion pitfalls, localeCompare, and the methods that take regular expressions.
kvi5hnuCode Sprout team member7 min readOn this page
JavaScript strings come with dozens of built-in methods. You'll use about fifteen of them every day, and each has an edge case or two that shows up in bugs and interviews. This article groups them by job, with runnable examples for each. Remember the golden rule from article 14: strings are immutable, so every method here returns a new string (or another value) and leaves the original unchanged.
Extracting part of a string
slice
s.slice(start, end) returns the code units from start up to, but not including, end. The easiest way to think about it is that indexes are cuts between characters:

const lang = "JavaScript";
console.log(lang.slice(0, 4)); // from cut 0 to cut 4
console.log(lang.slice(4)); // omit end: to the end of the string
console.log(lang.slice(-6)); // negative: count from the end
console.log(lang.slice(2, -2)); // mix positive and negative
console.log(JSON.stringify(lang.slice(5, 2))); // start after end: empty string
console.log(lang.slice()); // a full copy (rarely needed: strings are immutable)
Java
Script
Script
vaScri
""
JavaScript
substring and substr
substring(start, end) looks like slice but treats arguments differently: negative numbers become 0, and if start > end it swaps them. substr(start, length) takes a length instead of an end, and is a legacy feature (it's in the specification's Annex B for web compatibility). Prefer slice everywhere: it's the one that matches arrays' slice and handles negatives sensibly.
const s = "Hello, world";
console.log(s.slice(4, 1), "|", s.substring(4, 1)); // substring swaps
console.log(s.slice(-5), "|", s.substring(-5)); // substring treats -5 as 0
console.log(s.substr(7, 3)); // legacy: start 7, length 3
| ell
world | Hello, world
wor
Single characters
s[i], s.at(i) and s.charAt(i) return one code unit. at also accepts negative indexes (s.at(-1) is the last), and charAt returns "" instead of undefined when out of range. s.charCodeAt(i) and s.codePointAt(i) return numbers; article 14 explains the difference.
Searching
const log = "GET /api/users 200; GET /api/orders 500";
console.log(log.includes("500")); // is it there?
console.log(log.startsWith("GET")); // at the beginning?
console.log(log.endsWith("500")); // at the end?
console.log(log.indexOf("GET")); // first position
console.log(log.indexOf("GET", 1)); // first position at or after index 1
console.log(log.lastIndexOf("GET")); // last position
console.log(log.indexOf("DELETE")); // not found
console.log(log.startsWith("api", 5)); // check at a given position
true
true
true
0
20
20
-1
true
Common mistakes:
if (s.indexOf(x))is a bug.indexOfreturns0when the match is at the start, which is falsy, and-1when not found, which is truthy: the exact opposite of what you meant. Useincludes, or compare:s.indexOf(x) !== -1.- All of these are case-sensitive. For a case-insensitive check, lowercase both sides (
s.toLowerCase().includes(q.toLowerCase())) or use a regex with theiflag. - Searching for the empty string always succeeds:
s.includes("")istrueands.indexOf("")is0.
Replacing
replace(pattern, replacement) replaces the first match of a string pattern. replaceAll (ES2021) replaces every match:
const path = "src/app/main.js";
console.log(path.replace("/", "\\")); // only the first
console.log(path.replaceAll("/", "\\")); // all of them
console.log("a.b.c".replaceAll(".", "-")); // strings are literal: . is just a dot
console.log("hello world".replace(/o/g, "0")); // a regex with g also replaces all
src\app/main.js
src\app\main.js
a-b-c
hell0 w0rld
When the pattern is a regular expression, replaceAll requires the g flag (otherwise it throws a TypeError), and replace replaces all matches only if the regex has g.
Special $ patterns
The replacement string isn't fully literal: a $ starts a special pattern. This surprises people who insert prices or user input:
| Pattern | Inserts |
|---|---|
$$ | a literal $ |
$& | the matched text |
$` | the text before the match |
$' | the text after the match |
$1, $2... | regex capture groups |
$<name> | a named capture group |
const template = "Total: PRICE";
console.log(template.replace("PRICE", "$5")); // fine: $5 isn't special for string patterns
console.log(template.replace("PRICE", "$&!")); // $& is the match itself
console.log(template.replace("PRICE", "$$10")); // $$ becomes a single $
const userText = "$& wins";
console.log(template.replace("PRICE", () => userText)); // a function's result is literal
Total: $5
Total: PRICE!
Total: $10
Total: $& wins
Rule of thumb: when the replacement comes from data you don't control, pass a function. Its return value is inserted literally, and a function also lets you compute each replacement from the match:
const title = "the lord of the rings";
console.log(title.replace(/\b\w/g, letter => letter.toUpperCase()));
const prices = "apple 1.5, pear 2.25";
console.log(prices.replace(/\d+(\.\d+)?/g, amount => "$" + Number(amount).toFixed(2)));
The Lord Of The Rings
apple $1.50, pear $2.25
To build a regex from user input, escape it first so characters like . and * lose their special meaning. ES2025 added RegExp.escape for this, supported in current browsers and Node.js 24 and later:
const search = "1+1";
const pattern = new RegExp(RegExp.escape(search), "g");
"1+1=2, 1+1 again".replace(pattern, "two"); // "two=2, two again"
Part 11 covers regular expressions in full.
Splitting and joining
split(separator, limit) breaks a string into an array. The edge cases are where bugs hide:
console.log("a,b,,c".split(",")); // empty fields are kept
console.log("a b c".split(" ")); // two spaces make an empty field
console.log("a b c".split(/\s+/)); // a regex splits on runs of whitespace
console.log("a,b,c".split(",", 2)); // limit the number of pieces
console.log("abc".split("")); // into code units
console.log("".split(",")); // an empty string gives [""], not []
console.log("2026-11-18".split("-").map(Number));
console.log(["x", "y", "z"].join(" / ")); // the opposite: join an array
[ 'a', 'b', '', 'c' ]
[ 'a', 'b', '', 'c' ]
[ 'a', 'b', 'c' ]
[ 'a', 'b' ]
[ 'a', 'b', 'c' ]
[ '' ]
[ 2026, 11, 18 ]
x / y / z
Two classic bugs: splitting an empty line gives [""] (one empty field, not zero), so check for empty input first; and split("") splits emoji into broken halves, so use [...s] for characters. Don't parse CSV with split(","): quoted fields can contain commas. Use a CSV library.
Trimming and padding
const raw = " \t ada@example.com \n";
console.log(JSON.stringify(raw.trim())); // both ends
console.log(JSON.stringify(raw.trimStart())); // the start only
console.log(JSON.stringify(raw.trimEnd())); // the end only
console.log("7".padStart(3, "0")); // zero-pad to width 3
console.log("42".padStart(6), "|"); // pad with spaces (the default)
console.log("Name".padEnd(10, "."), "Ana"); // align columns
console.log("abc".padStart(2)); // already long enough: unchanged
console.log("ab".padEnd(7, "123")); // the filler repeats and is cut to fit
console.log("-".repeat(20));
"ada@example.com"
"ada@example.com \n"
" \t ada@example.com"
007
42 |
Name...... Ana
abc
ab12312
--------------------
trim removes all whitespace and line terminators, including tabs, newlines, non-breaking spaces and other Unicode spaces. trimLeft and trimRight are old aliases of trimStart and trimEnd.
Changing case
toUpperCase() and toLowerCase() use Unicode's rules, which have surprises beyond English:
console.log("straße".toUpperCase()); // ß has no single uppercase letter
console.log("straße".toUpperCase().length); // so the length changes!
console.log("TITLE".toLowerCase());
console.log("I".toLowerCase(), "I".toLocaleLowerCase("tr")); // Turkish has a dotless i
console.log("istanbul".toLocaleUpperCase("tr"));
STRASSE
7
title
i ı
İSTANBUL
Two lessons. First, case conversion can change the length, so never assume s.toUpperCase()[i] corresponds to s[i]. Second, use the toLocale... versions with an explicit locale for user-facing text in languages with special rules (Turkish and Azeri are the famous ones). For case-insensitive comparison, don't lowercase at all; use localeCompare with a sensitivity option:
const same = (a, b) => a.localeCompare(b, undefined, { sensitivity: "accent" }) === 0;
console.log(same("Hello", "hello")); // case ignored
console.log(same("cafe", "café")); // accents still count with "accent"
console.log("a".localeCompare("b"), "b".localeCompare("a"), "a".localeCompare("a"));
true
false
-1 1 0
localeCompare returns a negative number, zero or a positive number, the shape that sort expects (the exact values aren't guaranteed to be -1 and 1, only their sign).
Other useful methods
| Method | What it does | Example |
|---|---|---|
repeat(n) | concatenates n copies | "ab".repeat(3) is "ababab" |
concat(...values) | joins values; just use + or a template | "a".concat(1, 2) is "a12" |
normalize(form) | Unicode normalization (article 7) | "é".normalize("NFD").length is 2 |
isWellFormed(), toWellFormed() | detect and fix lone surrogates (article 14) | |
String.fromCharCode(...), String.fromCodePoint(...) | build a string from code numbers | String.fromCodePoint(0x1F680) is a rocket |
localeCompare(other, locale, options) | human ordering and comparison | |
match, matchAll, search, split, replace with a regex | pattern matching | see part 11 |
A quick look at the regex-based methods, which part 11 covers in depth:
const text = "Order 66 shipped in 3 boxes, 12 items";
console.log(text.search(/\d/)); // index of the first match
console.log(text.match(/\d+/g)); // all matches
for (const m of text.matchAll(/(\d+) (\w+)/g)) { // every match, with groups and positions
console.log(m.index, m[1], m[2]);
}
6
[ '66', '3', '12' ]
6 66 shipped
20 3 boxes
29 12 items
Methods are chainable
Because each method returns a new string, you can chain them into small pipelines:
function slugify(title) {
return title
.normalize("NFKD") // split accents from letters
.replace(/\p{M}/gu, "") // drop the accent marks
.toLowerCase()
.trim()
.replace(/[^a-z0-9]+/g, "-") // runs of anything else become one dash
.replace(/^-|-$/g, ""); // no dash at either end
}
console.log(slugify(" Crème Brûlée: A Beginner's Guide! "));
console.log(slugify("10 Tips & Tricks"));
creme-brulee-a-beginner-s-guide
10-tips-tricks
Common questions
What's the difference between slice and substring, and which should I use?
They agree for normal, in-order, non-negative arguments. slice supports negative indexes (counting from the end) and returns "" if start is after end; substring turns negatives into 0 and swaps reversed arguments. Use slice: it's consistent with Array.prototype.slice.
Why didn't replace change my string?
Strings are immutable: replace returns a new string. Write s = s.replace(...). Also check whether you needed replaceAll (or a regex with g), because replace with a string pattern changes only the first match.
Is there a contains method?
No; it's called includes (ES2015). It was going to be contains, but that name broke an old, widely used library that had added its own String.prototype.contains, so the committee renamed it.
How do I capitalize the first letter of a string?
s.charAt(0).toUpperCase() + s.slice(1). charAt(0) returns "" for an empty string, so it works for "" too. For text that may start with an emoji or a letter outside the Basic Multilingual Plane, split by code point first: the code below.
const [first = "", ...rest] = s;
first.toUpperCase() + rest.join("")
Summary
- Use
slice(start, end)to extract: indexes are cuts between characters, negatives count from the end. Avoid the legacysubstr. includes,startsWith,endsWithanswer yes/no;indexOfreturns a position or -1 (never use its result directly as a boolean).replacechanges the first string match,replaceAllevery match. Beware$patterns in replacement strings; pass a function for literal or computed replacements.splitkeeps empty fields and turns""into[""]; split on a regex for flexible separators.trim*,padStart/padEndandrepeathandle whitespace and formatting.- Case conversion follows Unicode and can change the length; use locale versions and
localeComparewithsensitivityfor comparisons.
Practice Questions
What does "banana".replace("a", "o") return? And "banana".replaceAll("a", "o")?
Answer
"bonana" and "bonono". A string pattern in replace changes only the first match.
What's wrong with this code?
if (email.indexOf("@")) {
...
}
Answer
For an address starting with @, indexOf returns 0, which is falsy, and for a string with no @ it returns -1, which is truthy. Use email.includes("@").
What do "abc".slice(-2) and "abc".substring(-2) return?
Answer
"bc" and "abc". slice counts -2 from the end; substring treats negative numbers as 0.
Write an expression that formats the number 5 as "005" and 123 as "123".
Answer
String(n).padStart(3, "0"). Padding only adds characters when the string is shorter than the target length.
What does "x,y,".split(",") return, and why might that matter when parsing input?
Answer
["x", "y", ""]. A trailing separator produces an empty final field. When parsing lines or lists, filter out empty strings (.filter(Boolean)) or trim the input first.
Previous: JavaScript Strings: Literals, Escape Sequences and UTF-16 Code Units
Next: JavaScript Template Literals: Interpolation, Multi-line Strings, Tagged Templates and String.raw

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.