3种js实现string的substring方法
最近遇到一个题目,“如何利用javascript实现string的substring方法?”我目前想到的有以下三种方案:
方法一:用charAt取出截取部分:
String.prototype.mysubstring=function(beginIndex,endIndex){ varstr=this, newArr=[]; if(!endIndex){ endIndex=str.length; } for(vari=beginIndex;i<endIndex;i++){ newArr.push(str.charAt(i)); } returnnewArr.join(""); } //test "Helloworld!".mysubstring(3);//"loworld!" "Helloworld!".mysubstring(3,7);//"low"
方法二:把字符串转换成数组然后取出需要部分:
String.prototype.mysubstring=function(beginIndex,endIndex){ varstr=this, strArr=str.split(""); if(!endIndex){ endIndex=str.length; } returnstrArr.slice(beginIndex,endIndex).join(""); } //test console.log("Helloworld!".mysubstring(3));//"loworld!" console.log("Helloworld!".mysubstring(3,7));//"low"
方法三:取出头尾部分,然后用replace去掉多余部分,适用于beginIndex较小,字符串长度-endIndex较小的情况:
String.prototype.mysubstring=function(beginIndex,endIndex){ varstr=this, beginArr=[], endArr=[]; if(!endIndex){ endIndex=str.length; } for(vari=0;i<beginIndex;i++){ beginArr.push(str.charAt(i)); } for(vari=endIndex;i<str.length;i++){ endArr.push(str.charAt(i)); } returnstr.replace(beginArr.join(""),"").replace(endArr.join(""),""); } //test console.log("Helloworld!".mysubstring(3));//"loworld!" console.log("Helloworld!".mysubstring(3,7));//"low"
以上3种js实现string的substring方法大家都可以尝试一下,比较一下哪种方法更方便,希望本文对大家的学习有所帮助。