slice(),substr()和substring()參數及返回值的區別

這三個方法都是Sring類型的基於字符串產生子字符串的方法,所以這三個方法都不會對原字符串產生什麼影響。

slice(start, end);
substring(start, end);
substr(start, len);

這三個方法的第一個參數都是start,即起始下標。

var s = "hello world";
console.log(s.length); //11
console.log(s.slice(-1)); //d
console.log(s.substring(-1)); //"hello world"
console.log(s.substr(-1)); //"d"
console.log(s.slice(-15)); //"hello world"
console.log(s.substring(-15)); //"hello world"
console.log(s.substr(-15)); //"hello world"

當start爲負數時,substring()返回原字符串。如果start小於0減字符串長度,substr()和slice()返回原字符串,否則返回結果與(start+length)相同。

console.log(s.slice(0, -1)); //'hello worl'
console.log(s.slice(0, -12)); //''
console.log(s.substring(0, -1)); //''
console.log(s.substr(0, -1)); //''

當第二個參數爲負數且(end+length)>0時,slice()方法的返回值同slice(start, (end+length)),第二個參數爲負數的其餘情況都返回空串。若第二參數超出範圍則子字符串會取到原字符串的最後一位。

console.log(s.slice(2, 12)); //'llo world'
console.log(s.substr(2, 10)); //'llo world'

發佈了35 篇原創文章 · 獲贊 15 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章