String.prototype.slice()
slice(start[, end]) Returns:
string · Added in vES3 · Updated March 13, 2026 · String Methods string slice substring es3
slice() extracts a portion of a string and returns it as a new string. The original string remains unchanged. This method is useful when you need to extract substrings based on positions, whether counting from the start or from the end using negative indices.
Syntax
slice(start)
slice(start, end)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
start | number | — | Index where extraction begins. Negative indices count from the end of the string. |
end | number | string.length | Index where extraction ends (exclusive). Negative indices count from the end. |
Examples
Extracting from the start
const greeting = "Hello, World!";
// Extract first 5 characters
console.log(greeting.slice(0, 5));
// Hello
// Omitting end extracts to the end of the string
console.log(greeting.slice(7));
// World!
Using negative indices
const text = "Hello, World!";
// Extract last 6 characters
console.log(text.slice(-6));
// World!
// Extract middle portion using negative end index
console.log(text.slice(0, -1));
// Hello, World
When start exceeds length
const str = "Hello";
// If start is greater than or equal to string length, returns empty
console.log(str.slice(10));
// (empty string)
console.log(str.slice(5));
// (empty string)
Start greater than end
const str = "Hello";
// When start is greater than end, slice() returns empty string
console.log(str.slice(5, 0));
// (empty string)
Common Patterns
Extract file extension from filename
const filename = "report.pdf";
const ext = filename.slice(filename.lastIndexOf("."));
console.log(ext);
// .pdf
Get last N characters
const id = "user-12345";
const suffix = id.slice(-5);
console.log(suffix);
// 12345
Truncate text with ellipsis
const longText = "This is a very long description that needs truncating";
const maxLength = 20;
const truncated = longText.length > maxLength
? longText.slice(0, maxLength) + "..."
: longText;
console.log(truncated);
// This is a very long...
Remove surrounding quotes or brackets
const quoted = "\"Hello World\"";
const unquoted = quoted.slice(1, -1);
console.log(unquoted);
// Hello World
Extract domain from URL
const url = "https://api.example.com/v1/users";
const domain = url.slice(8, url.indexOf("/", 8));
console.log(domain);
// api.example.com
When to Use
Use slice() when you need to:
- Extract substrings with precise control over start and end positions
- Work with negative indices to count from the end
- Maintain consistency with Arrayslice() behavior
When Not to Use
Avoid slice() when:
- You need case-insensitive matching — use a regex or
toLowerCase()first - You’re searching for a substring by content — use
indexOf()orincludes()instead - You need the argument-swap behavior that
substring()provides
See Also
- string::split — Split string into array
- string::substring — Similar method with different index handling