JavaScript等价于python字符串切片

Mic*_*rtz 6 javascript string python-2.7

是否有一个JavaScript等效于此Python的字符串切片方法?

s1 = 'stackoverflow'
print s1[1:]
# desired output
tackoverflow

var s2 = "stackoverflow";
/* console.log(s2.slice(1,));      this code crashes */

console.log(s2.slice(1, -1));
/* output doesn't print the 'w' */
tackoverflo
Run Code Online (Sandbox Code Playgroud)

ato*_*ool 8

参见Array.prototype.sliceString.prototype.slice

'1234567890'.slice(1, -1);            // String
'1234567890'.split('').slice(1, -1);  // Array
Run Code Online (Sandbox Code Playgroud)

然而Python切片有步骤:

'1234567890'[1:-1:2]
Run Code Online (Sandbox Code Playgroud)

*.prototype.slice没有step参数。为了解决这个问题,我写了slice.js。安装:

npm install --save slice.js
Run Code Online (Sandbox Code Playgroud)

用法示例:

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'
Run Code Online (Sandbox Code Playgroud)


Lau*_*ine 5

s2.slice(1)无需逗号即可简单使用。

  • 准确地说,语法是 object.slice(start, end) (4认同)