js中string的三種創(chuàng)建新字符串(截?。┓椒?/h2>

在字符串中創(chuàng)建新字符串的方法我們今天介紹三種,slice、substringsubstr

我們先介紹一下它們?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));   //""(空字符串)

看完例子是不是清晰了很多?。?!

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容