Sub topic 6
Extracting Substrings with slice and substring
This chapter assumes you know basic JavaScript syntax, can run code in Node.js or a browser console, and have read the earlier chapters on indexing and searching. In particular, you should know that indexOf and lastIndexOf return -1 when they find nothing.
The working model
Both slice(start, end) and substring(start, end) return a new string. The new string runs from index start up to, but not including, index end. If you leave out end, the result runs to the end of the string. Neither method changes the original string.
const word = "JavaScript";
console.log(word.slice(0, 4)); // Java
console.log(word.substring(0, 4)); // Java
console.log(word.slice(4)); // Script
console.log(word.length - 4); // 6, the length of "Script"Because end is exclusive, end - start always equals the length of the result, as long as both indexes are valid and in order.
Where the two methods differ
The methods behave differently when the arguments are negative or out of order.
| Input | `slice` | `substring` |
|---|---|---|
| Negative index | Counts back from the end (`length + n`) | Treated as `0` |
| `start > end` | Returns `""` | Swaps the two arguments |
| Index past `length` | Clamped to `length` | Clamped to `length` |
| `NaN` or missing `start` | Treated as `0` | Treated as `0` |
const s = "hello";
console.log(s.slice(-3)); // llo
console.log(s.substring(-3)); // hello (negative treated as 0)
console.log(s.slice(-3, -1)); // ll
console.log(s.substring(-3, -1)); // "" (both become 0)
console.log(s.slice(4, 1)); // "" (start is after end)
console.log(s.substring(4, 1)); // ell (swapped to 1, 4)
console.log(s.slice(2, 100)); // llo (clamped)Combining slice with search methods
In practice you usually compute the indexes with a search method.
const path = "/docs/guide/strings.md";
const file = path.slice(path.lastIndexOf("/") + 1);
console.log(file); // strings.md
const dot = file.lastIndexOf(".");
const name = file.slice(0, dot);
const ext = file.slice(dot + 1);
console.log(name, ext); // strings mdCommon errors
- Forgetting the
-1case. IflastIndexOffinds nothing, it returns-1. Thenfile.slice(0, -1)quietly drops the last character, andfile.slice(-1 + 1)returns the whole string. Check for-1before you slice. - Treating
endas a length.s.slice(2, 3)returns one character, not three. - Expecting negative indexes to work in
substring. They become0, which usually gives you more text than you wanted and no error. - Relying on the swap in
substring. When the arguments come out in the wrong order,substringhides the bug instead of returning an empty result.
function extension(fileName) {
const dot = fileName.lastIndexOf(".");
return dot === -1 ? "" : fileName.slice(dot + 1);
}
console.log(extension("notes.txt")); // txt
console.log(extension("README")); // ""Exercise
Given const s = "abcdef", what do s.slice(-4, -1), s.substring(-4, -1), and s.substring(5, 2) return, and why?
Show answer
s.slice(-4, -1) returns "cde" because the negative indexes become 6-4=2 and 6-1=5. s.substring(-4, -1) returns "" because both negative arguments become 0. s.substring(5, 2) returns "cde" because substring swaps the arguments to (2, 5).
Exercise
Write an expression that returns the last three characters of any string str, and returns the whole string when it has fewer than three characters.
Show answer
str.slice(-3). For a string shorter than three characters, length - 3 is negative, so slice clamps it to 0 and returns the whole string.