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

JS String

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

Or, Buy JavaScript in Depth

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

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog