字符串slice()、substr() 和 substring()的區(qū)別

var str = "hello world";
    console.log(str.slice(3));    //"lo world"
    console.log(str.substring(3));  //"lo world"
    console.log(str.substr(3));    //"lo world"
    console.log(str.slice(3,7));   //"lo w"
    console.log(str.substring(3,7)); //"lo w"
    console.log(str.substr(3,7));  //"lo worl"

在傳遞給這些方法的參數(shù)是負(fù)數(shù)的情況時,他們的行為就不相同了。

````
var str = "hello world";
console.log(str.slice(-3));    //"rld"  
console.log(str.substring(-3);  //"hello world"  此方法的參數(shù)是負(fù)數(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ù)作為開始位置
console.log(str.substr(3,-4));  //""(空字符串)

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

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

  • 第5章 引用類型(返回首頁) 本章內(nèi)容 使用對象 創(chuàng)建并操作數(shù)組 理解基本的JavaScript類型 使用基本類型...
    大學(xué)一百閱讀 3,679評論 0 4
  • 官網(wǎng) 中文版本 好的網(wǎng)站 Content-type: text/htmlBASH Section: User ...
    不排版閱讀 4,714評論 0 5
  • 第3章 基本概念 3.1 語法 3.2 關(guān)鍵字和保留字 3.3 變量 3.4 數(shù)據(jù)類型 5種簡單數(shù)據(jù)類型:Unde...
    RickCole閱讀 5,514評論 0 21
  • 一位朋友說:如果再年輕10年,我會寫出更好的東西。 她在感嘆時間。 是的,人到中年,沒有比這個時候更感覺時間金貴了...
    袋鼠MM簡單閱讀 270評論 0 4
  • 但凡是有孩子的家庭,“分享”這個詞的出鏡率總是高高在上,僅次于“慢點(diǎn)”“再吃一口”。畢竟我們或多或少的在報紙上,網(wǎng)...
    甜豌豆閱讀 530評論 0 3

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