3种js实现string的substring方法
最近遇到一个题目,“如何利用javascript实现string的substring方法?”我目前想到的有以下三种方案:
方法一:用charAt取出截取部分:
String.prototype.mysubstring=function(beginIndex,endIndex){
varstr=this,
newArr=[];
if(!endIndex){
endIndex=str.length;
}
for(vari=beginIndex;i<endIndex;i++){
newArr.push(str.charAt(i));
}
returnnewArr.join("");
}
//test
"Helloworld!".mysubstring(3);//"loworld!"
"Helloworld!".mysubstring(3,7);//"low"
方法二:把字符串转换成数组然后取出需要部分:
String.prototype.mysubstring=function(beginIndex,endIndex){
varstr=this,
strArr=str.split("");
if(!endIndex){
endIndex=str.length;
}
returnstrArr.slice(beginIndex,endIndex).join("");
}
//test
console.log("Helloworld!".mysubstring(3));//"loworld!"
console.log("Helloworld!".mysubstring(3,7));//"low"
方法三:取出头尾部分,然后用replace去掉多余部分,适用于beginIndex较小,字符串长度-endIndex较小的情况:
String.prototype.mysubstring=function(beginIndex,endIndex){
varstr=this,
beginArr=[],
endArr=[];
if(!endIndex){
endIndex=str.length;
}
for(vari=0;i<beginIndex;i++){
beginArr.push(str.charAt(i));
}
for(vari=endIndex;i<str.length;i++){
endArr.push(str.charAt(i));
}
returnstr.replace(beginArr.join(""),"").replace(endArr.join(""),"");
}
//test
console.log("Helloworld!".mysubstring(3));//"loworld!"
console.log("Helloworld!".mysubstring(3,7));//"low"
以上3种js实现string的substring方法大家都可以尝试一下,比较一下哪种方法更方便,希望本文对大家的学习有所帮助。
热门推荐
7 简短的二胎祝福语
10 简短霸气女儿生日 祝福语
11 祝福语高考小众诗句简短
12 元旦祝福语20秒简短
13 老师过年祝福语大全 简短
14 一生祝福语简短
15 产检祝福语简短霸气
16 朋友店开张祝福语简短
17 生日爱情祝福语大全简短
18 朋友女儿生日祝福语 简短