Syntax
str.slice(start, end)
str.substring(start, end)Examples
slice() - The Recommended Choice
Extracting substrings, including with negative indices.
const text = "Hello World";
console.log(text.slice(0, 5)); // "Hello"
console.log(text.slice(6)); // "World"
console.log(text.slice(-5)); // "World" - last 5 characterssubstring() and Its Quirks
Similar to slice(), but with different edge-case handling.
const text = "Hello World";
console.log(text.substring(0, 5)); // "Hello" - same as slice() here
console.log(text.substring(-3)); // "Hello World" - negative treated as 0!
console.log(text.substring(5, 0)); // "Hello" - swaps arguments if start > endBest practices
- Prefer slice() over substring() and substr() - it has more predictable, useful behavior with negative indices and no deprecated status
- Avoid substr() entirely in new code - it is deprecated, even though many browsers still support it
- Remember all three treat the end index as exclusive - slice(0, 5) gets characters at indices 0 through 4
- Use negative indices with slice() to extract from the end without manually calculating string.length - n
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification