Recently encountered a topic, "How to use JavaScript to implement the string substring method?" "I now think of the following three kinds of options:
method One: Use Charat to remove the interception 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 Two: Converts a string into an array and then takes 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 Three: Take out the tail part, and then remove the excess parts with replace, apply to beginindex small, string length-endindex small situation:
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"
The above 3 kinds of JS implement string substring method Everyone can try, compare which method is more convenient, I hope this article for everyone's learning help.