2015-09-01 77 views
1

是否存在與此Python字符串切片方法等效的JavaScript?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 

回答

3

只需使用s2.slice(1)即可,不使用逗號。

2

或者你可以使用substr

s2 = s1.substr(1); 
2

只是改變

console.log(s2.slice(1,-1)); 

console.log(s2.slice(1,s2.length)); 

您可以在MDN

查詢進一步資訊

+0

兩個指數(參數)都是_zero-based_。所以你的代碼是不正確的。爲了得到''w''(與OP想要的一樣),應該使用's2.slice(-1)'。 – hindmost

+0

它適用於所需的輸出:tackoverflow,就像你在編輯中看到的一樣。它提供了相同的輸出作爲接受的答案 –

0

數組和字符串的原型具有功能slice在JavaScript,下面演示:

「1234567890'.slice(1,-1); //字符串 '1234567890'.split('')。slice(1,-1); // array

但是slice沒有名爲step的參數。我們應該爲它做一個包裝。

在Python中,我們採用分片這樣的:

a = '1234567890'; 
a[1:-1:2]; 

這裏就像是巨蟒,命名爲slice.js項目的包裝,並使其在JS蟒蛇切片啓用,包括step

npm i --save slice.js 

然後使用它。

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' 
+0

請[編輯](編輯)(https://stackoverflow.com/posts/49152041/edit)你的答案解釋這段代碼如何回答這個問題,也許爲什麼這會比目前接受的答案。 –