Codectionary / Developer documentation / JavaScript

slice(), substring(), substr()

These three methods extract a portion of a string as a new string. slice() and substring() are similar, but slice() accepts negative indices (counting from the end) while substring() treats negative values as 0 and swaps arguments if start is greater than end. substr() (deprecated) uses a start index and a length rather than an end index.

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 characters

substring() 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 > end

Best 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

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation