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 NON-ASCII character, the result may not be expected.

[see JS: Character, Code Unit, Codepoint]

JS substring

  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, Codepoint
  4. String Escape Sequence
  5. Unicode Escape Sequence

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

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

Web Dev Tutorials