最近遇到一個題目,“如何利用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方法大家都可以嘗試一下,比較一下哪種方法更方便,希望本文對大家的學習有所幫助。
新聞熱點
疑難解答