3种js实现string的substring方法

(编辑:jimmy 日期: 2024/10/5 浏览:2)

最近遇到一个题目,“如何利用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方法大家都可以尝试一下,比较一下哪种方法更方便,希望本文对大家的学习有所帮助。

一句话新闻

微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。