Three js substring methods to implement string
- 2020-10-23 20:02:22
- OfStack
Recently, I encountered a question, "How to use javascript to realize the substring method of string? At present, I have come up with the following three schemes:
Method 1: Extract the interception 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 pull 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 remove the excess parts with replace. It is suitable for the case that beginIndex is small and string length -ES16en 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"
All the above three js substring methods to achieve string can be tried under 1 to compare which method is more convenient, I hope this article will be helpful for you to learn.