'JavaScript equivalent of python string slicing
Is there a JavaScript equivalent to this Python method of string slicing?
>>> 'stackoverflow'[1:]
'tackoverflow'
I have tried:
// this crashes
console.log("stackoverflow".slice(1,));
// output doesn't print the last letter 'w'
console.log("stackoverflow".slice(1, -1));
// tackoverflo
Solution 1:[1]
Simply use s2.slice(1)
without the comma.
Solution 2:[2]
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'
Solution 3:[3]
Or you could use substr
s2 = s1.substr(1);
Solution 4:[4]
SLICE
Slice is a JavaScript implementation of Python's awesome negative indexing and extended slice syntax for arrays and strings. It uses ES6 proxies to allow for an intuitive double-bracket indexing syntax which closely replicates how slices are constructed in Python. Oh, and it comes with an implementation of Python's range method too!
I know a package that solves this exact problem.
It's called
you can literally do with arrays and string whatever you do in python.
to install this package:
yarn add slice
// or
npm install slice
Simple use cases
check out ? the docs ? for more.
Solution 5:[5]
just change
console.log(s2.slice(1,-1));
for
console.log(s2.slice(1,s2.length));
You can check further info on MDN
var s2 = "stackoverflow";
alert(s2.slice(1, s2.length));
Solution 6:[6]
If you need the step argument here is a solution
Array.prototype.slice_ = function(start,end,step=1) {
return this.slice(start,end)
.reduce((acc, e, i) => i % step == 0
? [...acc, e]
: acc, []);
}
console.log([1,2,3,4,5,6,7,8,9,10].slice_(1, 10, 2))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Lauromine |
Solution 2 | Mateen Ulhaq |
Solution 3 | andrew |
Solution 4 | Soorena |
Solution 5 | |
Solution 6 | geckos |