This article mainly introduces three methods for implementing the string substring in javascript. if you need it, refer to a question recently asked: "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
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
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.