首頁 > web前端 > js教程 > 主體

3種js實作string的substring方法_javascript技巧

WBOY
發布: 2016-05-16 15:33:04
原創
2029 人瀏覽過

最近遇到一個題目,「如何利用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("");
}

//test
console.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(""),"");
}

//test
console.log("Hello world!".mysubstring(3));//"lo world!"
console.log("Hello world!".mysubstring(3,7));//"lo w"
登入後複製

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

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!