JS: String.prototype.slice

By Xah Lee. Date: . Last updated: .

Return 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 codepoint is ≥ 2^16, the result may not be expected.

[see JS: Character, Code Unit, Code Point]

Reference

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

JavaScript substring Topic

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

String Topic

  1. JS: String Overview
  2. JS: Template String
  3. JS: String Escape Sequence
  4. JS: Unicode Escape Sequence
  5. JS: String Object
  6. JS: String.prototype
  7. JS: String to Number
  8. JS: Encode URL, Escape String
  9. JS: Format Number
  10. JS: JSON
  11. JS: Source Code Encoding
  12. JS: Allowed Characters in Identifier
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.