Three js methods to implement the string substring method, stringsubstring
Recently, I encountered a question: "How to use javascript to implement the string substring method ?" I have come up with the following three solutions:
Method 1: extract the captured part with 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"
Method 2: Convert the string into an array and extract the required part:
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"
Method 3: remove the header and tail parts, and use replace to remove the excess parts. This method is applicable when the beginIndex is small and the string length-endIndex is small:
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"
You can try the above three js methods to implement the string substring method and compare which method is more convenient. I hope this article will be helpful for your learning.