I recently encountered a question, "How to use JavaScript to implement the substring method of string?" I currently have the following three solutions in mind:
Method 1: Use charAt to extract the intercepted part:
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 take out 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(""); } //test console.log("Hello world!".mysubstring(3));//"lo world!" console.log("Hello world!".mysubstring(3,7));//"lo w"
Method 3: Take out the head and tail parts, and then use replace to remove the excess parts. It is suitable for situations where beginIndex is small and 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(""),""); } //test console.log("Hello world!".mysubstring(3));//"lo world!" console.log("Hello world!".mysubstring(3,7));//"lo w"
You can try the above three substring methods of string in js and compare which method is more convenient. I hope this article will be helpful to everyone's learning.