EN
JavaScript - String slice() method example
0
points
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 |
|
Parameters |
|
Result | A new string containing the sliced part of the string. |
Description |
The The method extracts up to |
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)); // ''