Welcome 微信登录

首页 / 脚本样式 / JavaScript / 3种js实现string的substring方法

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