Skip to content →

[JS] Slice、Substring、Substr截取、Split分割、Splice刪增

Slice(start, end):
不改變原始資料,創建新資料。

截取
var str = “Hi SLICE”;
str.slice();       //Hi SLICE ,效果同 str.slice(0);
str.slice(1, 5);    //i SL     ,到前一個數,不包含end
str.slice(1);     //i SLICE
str.slice(-1);     //E ,最後一字
str.slice(-4, 7);    //LIC

var arr = [“A”, “B”, “C”, “D”, “E”];
arr.slice();       //A,B,C,D,E ,效果同 arr.slice(0);
arr.slice(1, 5);    //B,C,D,E
arr.slice(-2);      //D,E
arr.slice(-4, -1);    //B,C,D
arr.slice(-4, 3);    //B,C


Substring(start, end):
與Slice相似,不接受負值。

截取
var str = “Hi SUBSTRING”;
str.substring();    //Hi SUBSTRING  ,效果同 str. substring(0);
str.substring(1, 5);  //i SL       ,到前一個數,不包含end
str.substring(7, 5);  //BS       ,start比end大時,兩個會調換 ,slice()沒作用
str.substring(1);    //i SUBSTRING
str.substring(-1);    //不接受負值


Substr(start, length):
與Slice相似,第二個參數是長度 。
ECMAscript沒標準化,少用。

截取
var str = “Hi SUBSTR Method”;
str. substr();       //Hi SUBSTR Method,效果同 str. substr(0);
str. substr(1);     //i SUBSTR Method
str. substr(-6, 5);   //Metho   ,字串長度


Split(separator, limit):
不改變原始字串,用separator分割成陣列。
Array.join()作用相反。

var str = “Hi SPLIT, Have A Nice Day.”;
str. split() ;       //Array[“Hi SPLIT, Have A Nice Day.”] ,效果同 str. split(0);
str. split(” “);     //Hi,SPLIT,,Have,A,Nice,Day.  ,同 str. split(/\s+/);
str. split(” “, 3);    //Hi,SPLIT,,Have
str.split(” “)[3];    //A
str. split(“”);     //H,i, ,S,P,L,I,T,,, ,H,a,v,e, ,A, ,N,i,c,e, ,D,a,y,.
str. split(“”, 11);    //H,i, ,S,P,L,I,T,,, ,H
str.split(“”)[11];    //a


Splice(start, deleteCount, addItem1,…,addItemx):
會改變原來陣列。

var arr = [“A”, “B”, “C”, “D”, “E”];
arr.splice();       //A,B,C,D,E ,同 str. splice(5);
arr.splice(0);     //清空陣列元素
arr.splice(1, 5);    //A
arr.splice(2);     //A,B
arr.splice(-2);     //A,B,C
arr.splice(4, -1);    //A,B,C,D,E ,deleteCount為0或負數,不刪除元素
arr.splice(2, 0, “f1”, “f2”); //A,B,f1,f2,C,D,E
arr.splice(2, 3, “f1”, “f2”); //A,B,f1,f2
arr.splice(-2, 3, “f1”);   //A,B,C,f1

Published in JS

Comments are closed.