JavaScript equivalent of python string slicing
See Array.prototype.slice
and String.prototype.slice
.
'1234567890'.slice(1, -1); // String
'1234567890'.split('').slice(1, -1); // Array
However, Python slices have steps:
'1234567890'[1:-1:2]
But *.prototype.slice
has no step
parameter. To remedy this, I wrote slice.js
. To install:
npm install --save slice.js
Example usage:
import slice from 'slice.js';
// for array
const arr = slice([1, '2', 3, '4', 5, '6', 7, '8', 9, '0']);
arr['2:5']; // [3, '4', 5]
arr[':-2']; // [1, '2', 3, '4', 5, '6', 7, '8']
arr['-2:']; // [9, '0']
arr['1:5:2']; // ['2', '4']
arr['5:1:-2']; // ['6', '4']
// for string
const str = slice('1234567890');
str['2:5']; // '345'
str[':-2']; // '12345678'
str['-2:']; // '90'
str['1:5:2']; // '24'
str['5:1:-2']; // '64'
Simply use s2.slice(1)
without the comma.