在字符串中創(chuàng)建新字符串的方法我們今天介紹三種,slice、substring、substr
我們先介紹一下它們?nèi)齻€的區(qū)別
str.slice(start, end), start<= 字符 < end , 如果是負數(shù)就是從后向前找;
str.substring(start, end),當參數(shù)為正數(shù)時start<= 字符 < end ,當參數(shù)為負數(shù)時,對應索引為0(無論是第一個參數(shù)還是第二個參數(shù))小的數(shù)為start, 大的數(shù)為end;
str.substr(index,howmany),第一個數(shù)為其實位置的下標,第二個數(shù)為要截取幾個;
下面我們用實際的例子來看看
var str = "hello world";
console.log(str.slice(6)); //"world"
console.log(str.substring(6)); //"world"
console.log(str.substr(6)); //"world"
當有一個參數(shù)的時候是不是三個都一樣
var str = "hello world";
console.log(str.slice(2,7)); //"llo w"
console.log(str.substring(2,7)); //"llo w"
console.log(str.substr(2,7)); //"llo worl"
同樣是(2,7)substr是不是就不一樣了呢,因為它的7是往后截取7個;
var str = "hello world";
console.log(str.slice(-3)); //"rld"
console.log(str.substring(-3); //"hello world" 此方法的參數(shù)是負數(shù)都轉(zhuǎn)換為0
console.log(str.substr(-3)); //"rld"
console.log(str.slice(3,-4)); //"lo w"
console.log(str.substring(3,-4)); //"hel" 負數(shù)對應索引為0;小的數(shù)為start, 大的數(shù)為end;所以它其實就變成了str.substring(0,3);
console.log(str.substr(3,-4)); //""(空字符串)
看完例子是不是清晰了很多?。?!