Languages
[Edit]
EN

JavaScript - String slice() method example

0 points
Created by:
Ela-Davey
663

The slice() method is used to extract a part of a string in JavaScript.

// ONLINE-RUNNER:browser;

var text = 'abcde';

console.log(text.slice(1)); // bcde
console.log(text.slice(2)); // cde

console.log(text.slice(1, 3));  // bc
console.log(text.slice(2, 4));  // cd

console.log(text.slice(-2));    // de
console.log(text.slice(2, -1)); // cd

1. Documentation

Syntax

slice(startIndex)

slice(startIndex, endIndex)

Parameters

startIndex - the index at which to begin extraction. If negative, the string is sliced from string.length + startIndex to the end of the string.

endIndex - the index of the first character to exclude from the returned substring.

ResultA new string containing the sliced part of the string.
Description

The slice() extracts some text from one string and returns it as a new string.

The method extracts up to endIndex (but not including).

2. Practical examples

Positive indexing

// ONLINE-RUNNER:browser;

var text = 'abcde';

console.log(text.slice());  // abcde
console.log(text.slice(1)); // bcde
console.log(text.slice(2)); // cde

console.log(text.slice(1, 3));  // bc
console.log(text.slice(1, 4));  // bcd

console.log(text.slice(2, 3));  // c
console.log(text.slice(2, 4));  // cd

Negative indexing

// ONLINE-RUNNER:browser;

var text = 'abcde';

console.log(text.slice(-1)); // e
console.log(text.slice(-2)); // de

console.log(text.slice(-3, -2));  // c
console.log(text.slice(-3, -1));  // cd

console.log(text.slice(-4, -2));  // bc
console.log(text.slice(-4, -1));  // bcd

Mixed

// ONLINE-RUNNER:browser;

var text = 'abcde';

console.log(text.slice(1, -2));  // bc
console.log(text.slice(1, -3));  // b

console.log(text.slice(2, -2));  // c
console.log(text.slice(2, -3));  // ''

References

  1. String.prototype.slice() - JavaScript | MDN

Alternative titles

  1. JavaScript - String.prototype.slice() documentation with examples
  2. js - String slice() method documentation with examples
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - String (documentation)

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join