slice and substring
Learn to slice parts of a string with slice and substring.
Taking a slice
The slice method returns a part of a string as a new string. The first argument is the start index and is included; the second argument is the end index and is excluded. For example "javascript".slice(0, 4) returns "java".
You can also pass negative indexes: -1 points to the last character and -3 to the third from the end. This lets you grab the tail of a string without knowing its length.
substring vs slice
The substring method does a similar job but with two important differences. First, it treats negative indexes as zero, so it never counts from the end. Second, if the start is greater than the end it swaps the two arguments.
So "javascript".substring(4, 0) behaves like substring(0, 4) and returns "java". When you need to count from the end, prefer slice; it is more predictable.
Exercise Take the file extension with a negative index
Use slice with a negative index to take the last three characters of filename and store them in ext. Print the result.
Show example solution
const filename = "report.pdf";
// take the last three characters with slice and a negative index
const ext = filename.slice(-3);
console.log(ext);
Exercise Take the start of a string with slice
Use slice(0, 10) to take the first ten characters of url and store them in head. Print the result.
Show example solution
const url = "https://x.com";
// take the first ten characters with slice
const head = url.slice(0, 10);
console.log(head);
Test yourself
-
What does "javascript".slice(0, 4) return?
"javascript".slice(0, 4)- "java"
- "javas"
- "javascript"
- "javs"
Show answer
"java" — Correct. slice includes the start and excludes the end; the first four characters are "java".
-
Take the "debl" part of "codeblanks" with slice
const site = "codeblanks"; const part = site.slice(____); console.log(part);Show answer
const site = "codeblanks"; const part = site.slice(2, 6); console.log(part); -
Match method to behavior
- slice(-2)
- last two characters
- substring(-2)
- empty string (treated as zero)
- slice(1, 4)
- from 1 to 4 (excluded)
- substring(4, 1)
- from 1 to 4 (swapped)