Code Logo

Extract with String.slice()

Published at25 Jul 2026
JavaScript String Handling Easy 0 views
Like0

Write a JavaScript function that takes a string, a start index, and an end index, and returns the extracted substring using String.slice(). The slice() method extracts a section of a string and returns it as a new string without modifying the original.

String.prototype.slice() extracts characters from a string. It takes two parameters: the beginning index (inclusive) and the ending index (exclusive). If the end index is omitted, slice extracts to the end of the string. Negative indices count from the end of the string, making slice() flexible for extracting from the end.

Unlike substring() which swaps negative values with 0, slice() treats negative indices as offsets from the end. This makes slice() the preferred method when you need to extract from the end of a string. If start is greater than end, slice() returns an empty string, unlike substring() which swaps them.

Time complexity is O(n) where n is the length of the extracted substring. Space complexity is O(n) for the new string. The original string is never modified as JavaScript strings are immutable.

Edge cases include negative indices (count from end), start greater than end (returns empty string), out-of-bounds indices (clamped to string length), and omitting the end parameter (extracts to end of string).

Example Input & Output

Example 1
Input
"hello world",6,11
Output
"world"
Explanation

Characters 6 to 11

Example 2
Input
"abcdef",-3
Output
"def"
Explanation

Last 3 characters using negative index

Example 3
Input
"javascript",4
Output
"script"
Explanation

From index 4 to end

Example 4
Input
"test",1,3
Output
"es"
Explanation

Middle substring

Example 5
Input
"hello world",0,5
Output
"hello"
Explanation

First 5 characters

Algorithm Flow

Recommendation Algorithm Flow for Extract with String.slice()
Recommendation Algorithm Flow for Extract with String.slice()

Solution Approach

function solution(str, start, end) {
  return str.slice(start, end);
}

Best Answers

javascript - Approach 1
function solution(str, start, end) {
  return str.slice(start, end);
}