Sub topic 6
Extracting Substrings with slice and substring
This chapter assumes you can already index into a string with brackets and at, as covered in the chapter on length and indexing. It also assumes you have used the search methods indexOf and lastIndexOf. You will use those methods here to find the positions you cut at.
A substring is a continuous run of characters taken from a larger string. JavaScript has two current methods for extracting one: slice and substring. Both take a start index and an optional end index. Both return a new string and leave the original unchanged. Their behavior differs when you pass negative, reversed, or unusual arguments, and those cases cause most of the bugs.
The Shared Model: Half-Open Ranges
Both methods use a half-open range. The start index is included and the end index is excluded. If you picture the indexes as the gaps between characters, the rule is easier to keep straight:
| Gap index | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| Character after the gap | h | e | l | l | o | (end) |
"hello".slice(1, 4) cuts at gap 1 and gap 4 and returns "ell". The half-open model has two useful properties:
- The length of the result is
end - startwhenever both indexes are valid andstart <= end. - Adjacent cuts fit together with no overlap.
s.slice(0, i) + s.slice(i)always rebuildss.
const s = "hello";
console.log(s.slice(1, 4)); // ell
console.log(s.substring(1, 4)); // ell
console.log(s.slice(2)); // llo (end defaults to length)
console.log(s.slice()); // hello (a full copy)
console.log(s.slice(0, 2) + s.slice(2) === s); // trueWith non-negative arguments in order, the two methods give identical results. The differences start outside that case.
How Each Method Resolves Its Arguments
Each method turns its raw arguments into two concrete gap positions and then extracts the text between them. The steps are the same up to the point where they handle negative values and reversed order.
slice: Negative Means "From the End"
slice reads a negative index as an offset from the end, so -1 means length - 1. This matches how at(-1) reads the last character. If the computed start is at or after the computed end, the result is an empty string. slice never reorders its arguments.
const s = "hello";
console.log(s.slice(-3)); // llo (last three characters)
console.log(s.slice(-3, -1)); // ll
console.log(s.slice(1, -1)); // ell (drop first and last)
console.log(s.slice(3, 1)); // "" (reversed range gives empty string)
console.log(s.slice(-10)); // hello (-10 + 5 = -5, clamped to 0)
console.log(s.slice(2, 100)); // llo (end clamped to 5)substring: Negative Means Zero, and Order Does Not Matter
substring clamps negative values to 0 and then swaps the arguments if the start is larger than the end.
const s = "hello";
console.log(s.substring(-3)); // hello (-3 becomes 0)
console.log(s.substring(3, 1)); // el (swapped to substring(1, 3))
console.log(s.substring(1, -1)); // h (-1 becomes 0, then swapped to substring(0, 1))
console.log(s.substring(2, 100)); // lloThe last line before it is a common surprise. Code written for slice(1, -1) ("drop the ends") returns just "h" when someone changes it to substring.
Side-by-Side Comparison
| Call on `"hello"` | `slice` | `substring` | Why they differ |
|---|---|---|---|
| `(1, 4)` | `"ell"` | `"ell"` | No difference |
| `(-3)` | `"llo"` | `"hello"` | slice counts from end; substring uses 0 |
| `(1, -1)` | `"ell"` | `"h"` | substring turns -1 into 0, then swaps |
| `(3, 1)` | `""` | `"el"` | substring swaps reversed arguments |
| `(2, null)` | `""` | `"he"` | null becomes 0; substring then swaps |
| `(NaN, 2)` | `"he"` | `"he"` | NaN becomes 0 in both |
| `(1.7)` | `"ello"` | `"ello"` | Fractions are truncated toward zero |
Edge Cases That Cause Real Bugs
null Is Not the Same as Omitting the End
Only undefined (or a missing argument) means "to the end of the string". null converts to 0. This matters when an end index comes from a variable that might be null.
const s = "hello";
const end = null;
console.log(s.slice(2, end)); // "" (end is 0)
console.log(s.slice(2, end ?? undefined)); // lloThe -1 From a Failed Search
indexOf and lastIndexOf return -1 when nothing is found. Passing that result straight into slice turns "not found" into "the last character".
const name = "README";
// Buggy: no dot, so lastIndexOf returns -1 and slice(-1) returns "E"
console.log(name.slice(name.lastIndexOf("."))); // E
function getExtension(fileName) {
const dot = fileName.lastIndexOf(".");
// dot > 0 also rejects dotfiles such as ".bashrc"
return dot > 0 ? fileName.slice(dot + 1) : "";
}
console.log(getExtension("archive.tar.gz")); // gz
console.log(getExtension("README")); // ""
console.log(getExtension(".bashrc")); // ""The + 1 pattern is safe in one common case. path.slice(path.lastIndexOf("/") + 1) turns -1 into 0 and returns the whole string when there is no slash, which is usually what you want for a file name.
const path = "/docs/guide/strings.md";
console.log(path.slice(path.lastIndexOf("/") + 1)); // strings.md
console.log("notes.txt".slice("notes.txt".lastIndexOf("/") + 1)); // notes.txtNegative Zero Is Still Zero
Building a negative end from a length works until the length is zero. -0 is just 0, so slice(0, -0) returns an empty string, not the whole string.
function removeSuffixBuggy(s, suffix) {
return s.endsWith(suffix) ? s.slice(0, -suffix.length) : s;
}
console.log(removeSuffixBuggy("report.txt", ".txt")); // report
console.log(removeSuffixBuggy("report.txt", "")); // "" (bug)
function removeSuffix(s, suffix) {
return s.endsWith(suffix) ? s.slice(0, s.length - suffix.length) : s;
}
console.log(removeSuffix("report.txt", "")); // report.txt
function removePrefix(s, prefix) {
return s.startsWith(prefix) ? s.slice(prefix.length) : s;
}
console.log(removePrefix("https://example.com", "https://")); // example.comOff-by-One in Truncation
To shorten text to a fixed width with an ellipsis, leave room for the ellipsis character.
function truncate(str, max) {
return str.length <= max ? str : str.slice(0, max - 1) + "…";
}
console.log(truncate("JavaScript strings", 10)); // JavaScrip…
console.log(truncate("short", 10)); // shortCutting Through a Surrogate Pair
Indexes count UTF-16 code units, not visible characters. An emoji outside the Basic Multilingual Plane takes two code units, and a cut between them leaves a broken half-character. The Unicode chapter covers this in depth. For now, know the symptom and the quick fix of slicing an array of code points.
const s = "a\u{1F600}b";
console.log(s.slice(0, 2).length); // 2, but the second unit is a lone surrogate
console.log([...s].slice(0, 2).join("")); // a😀 (sliced by code point)What About substr?
Older code uses substr(start, length), whose second argument is a length rather than an end index. It accepts a negative start: "hello".substr(-3, 2) returns "ll". The specification lists substr in Annex B, the section for legacy web-compatibility features, so avoid it in new code. You can replace it with slice(start, start + length) for non-negative starts. For negative starts, convert the start first.
const s = "hello";
console.log(s.substr(1, 3)); // ell (legacy)
console.log(s.slice(1, 1 + 3)); // ellChoosing a Method
| Situation | Use |
|---|---|
| Take the last N characters | `s.slice(-n)` |
| Drop the first and last character | `s.slice(1, -1)` |
| Cut between two positions of unknown order | `s.substring(a, b)` |
| Remove a known prefix or suffix | `startsWith`/`endsWith` with `slice` |
| Cut by visible character, emoji included | `[...s].slice(a, b).join("")` |
| Maintaining legacy `substr` code | Rewrite as `slice` |
Exercise
Predict each result for const s = "JavaScript": (a) s.slice(-6, -2), (b) s.substring(-6, 4), (c) s.slice(4, 0), (d) s.substring(4, 0).
Show answer
(a) "Scri": -6 becomes 4 and -2 becomes 8, giving indexes 4 to 8. (b) "Java": -6 becomes 0, giving indexes 0 to 4. (c) "": start 4 is not less than end 0, and slice does not swap. (d) "Java": substring swaps the arguments to (0, 4).
Exercise
Write a function between(s, open, close) that returns the text between the first occurrence of open and the next occurrence of close after it, or null if either is missing. For example, between("price: [42] USD", "[", "]") should return "42".
Show answer
function between(s, open, close) { const start = s.indexOf(open); if (start === -1) return null; const from = start + open.length; const end = s.indexOf(close, from); if (end === -1) return null; return s.slice(from, end); } Checking both -1 results before slicing stops a failed search from turning into a negative index.
Exercise
A teammate writes const base = file.slice(0, -ext.length) to strip an extension that is stored in ext without its dot, such as "md". Name two inputs where this gives the wrong result and give a fix.
Show answer
When ext is "", -0 is 0 and the result is an empty string. When the file name does not actually end with ext, unrelated characters are cut off. The dot is also left behind, so "notes.md" becomes "notes.". Fix: const suffix = "." + ext; const base = file.endsWith(suffix) ? file.slice(0, file.length - suffix.length) : file;