JavaScript: String.prototype.slice

By Xah Lee. Date: . Last updated: .

Returns a substring from index start to end.

By default, end is length of string.

(think of index as between the chars. Index 0 is before first character. Index 1 is after first character.)

Arguments start and end can be negative. If negative, index count start from the end, right to left. (-1 is the place between last character and second last character).

const ss = "abcd";

console.log ( ss.slice(1,3) ); // bc

// think of index as between characters
// index before first char is 0
// index after last char is length
// negative index counts from the end, right to left

console.log ( ss.slice(0, ss.length) ); // abcd
console.log ( ss.slice() ); // abcd
console.log ( ss.slice(1) ); // bcd
console.log ( ss.slice(-1) ); // d
console.log ( ss.slice(-2) ); // cd

// same index, empty string
console.log ( ss.slice(2, 2) === "" ); // true

// when start index is greater than end index, result is empty string
console.log ( ss.slice(3, 2) === "" ); // true
console.log ( ss.slice(-2, -3) === "" ); // true

Note: if you have character whose code point is ≥ 2^16, the result may not be expected.

〔►see JavaScript: String is 16-Bit Unit Sequence

Reference

ECMAScript 2015 §Text Processing#sec-string.prototype.slice

JavaScript substring Topic

  1. JavaScript: String.prototype.slice
  2. JavaScript: String.prototype.substring
  3. JavaScript: String.prototype.substr

String Topic

  1. JavaScript: Default Charset/Encoding
  2. JavaScript: String is 16-Bit Unit Sequence
  3. JavaScript: Unicode Character Escape Sequence
  4. JavaScript: Allowed Characters in Identifier
  5. HTML: Allowed Characters in id Attribute
  6. HTML: Character Sets and Encoding
  7. HTML XML Entities

  1. JavaScript: Template String
  2. JavaScript: Convert String to Number
  3. JavaScript Encode URL, Escape String
  4. JavaScript: Format Number
  5. JavaScript: JSON Object

  1. JavaScript: String Object
  2. JavaScript: String.prototype
  3. JavaScript: String Constructor
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.