1.Substring(x,y) : 輸出一個字符串,當其中只有一個參數時,會輸出從x開始到結尾的String。
舉例:
var str="hello";
console.log(str.substring(1));
輸出結果為ello
如果有兩個參數,則會輸出從x到y的值,值得注意的時候,這里的x ,y可以理解成一個
(x, y]的區間,即不包含第x個元素,但包含第y個元素, x,y均從1開始計算
舉例:
var str="helloworld";
console.log(str.substring(2,5));
輸出結果為llo。
另外當x<y的情況時,系統會自動調整x,y的位置並輸出也就是說
var str="helloworld";
console.log(str.substring(5,2));
這倆個結果是一樣的。
如y為負值,則直接輸出為x之前的字符串
舉例
var str="helloworld";
console.log(str.substring(3,-5));
結果為hel;
2.Substr(x,y): 和substring不同,substr內的x,y屬性分別代表元素的起始位置,及輸出的元素長度。舉例:
var str="helloworld";
console.log(str.substr(2,5));
輸出結果為:llowo
因為x,y兩個參數的屬性不同,所以相互調換位置時,並沒有歧義,而是正常輸出。但當y為負值時,則為空。
舉例:
var str="helloworld";
console.log(str.substr(3,-5));
結果為空
3.slice(x,y) 和substring類似,都是返回一個(x, y]區間的字符串,唯一不同需要注意的情況是,如果x>y的情況發生,則會產生一個空,而不會自動調換位置。舉例:
var str="helloworld";
console.log(str.slice(2,5));
輸出結果為llo
var str="helloworld";
console.log(str.slice(5,2));
結果為空
特別注意,在這里y可以為負值。輸出的的是y+length之后的長度,舉例:
var str="helloworld";
console.log(str.slice(3,-2));
輸出結果為 其length值為10,則真實輸出應為
3,(10-2); 結果為lowor