3種js實現string的substring方法,stringsubstring

來源:互聯網
上載者:User

3種js實現string的substring方法,stringsubstring

最近遇到一個題目,“如何利用javascript實現string的substring方法?”我目前想到的有以下三種方案:
方法一:用charAt取出截取部分:

String.prototype.mysubstring=function(beginIndex,endIndex){  var str=this,    newArr=[];  if(!endIndex){    endIndex=str.length;  }  for(var i=beginIndex;i<endIndex;i++){    newArr.push(str.charAt(i));  }  return newArr.join("");}//test"Hello world!".mysubstring(3);//"lo world!""Hello world!".mysubstring(3,7);//"lo w"

方法二:把字串轉換成數組然後取出需要部分:

String.prototype.mysubstring=function(beginIndex,endIndex){  var str=this,    strArr=str.split("");  if(!endIndex){    endIndex=str.length;  }  return strArr.slice(beginIndex,endIndex).join("");}//testconsole.log("Hello world!".mysubstring(3));//"lo world!"console.log("Hello world!".mysubstring(3,7));//"lo w"

 方法三:取出頭尾部分,然後用replace去掉多餘部分,適用於beginIndex較小,字串長度-endIndex較小的情況:

String.prototype.mysubstring=function(beginIndex,endIndex){  var str=this,    beginArr=[],    endArr=[];  if(!endIndex){    endIndex=str.length;  }  for(var i=0;i<beginIndex;i++){    beginArr.push(str.charAt(i));  }  for(var i=endIndex;i<str.length;i++){    endArr.push(str.charAt(i));  }  return str.replace(beginArr.join(""),"").replace(endArr.join(""),"");}//testconsole.log("Hello world!".mysubstring(3));//"lo world!"console.log("Hello world!".mysubstring(3,7));//"lo w"

以上3種js實現string的substring方法大家都可以嘗試一下,比較一下哪種方法更方便,希望本文對大家的學習有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.