---
title: "3种JavaScript实现string的substring方法"
author: "冰封王座"
date: "2016-03-10T20:07:28Z"
tags: []
categories: ["Web前端"]
slug: "3-javascript-string-substring"
draft: false
lastmod: "2016-03-10T20:07:28Z"
id: 2282005
url: "https://binfengwz.iteye.com/blog/2282005"
---

# 3种JavaScript实现string的substring方法

 

近来遇到一个题目，“若何把持javascript实现string的substring方法？”我今朝想到的有如下三种规划：

 

**方法一：用charAt掏出截取部份：**

String.prototype.mysubstring=function(beginIndex,endIndex){  
  var str=this,  
    newArr=\[];  
  if(!endIndex){  
    endIndex=str.length;  
  }  
  for(var i=beginIndex;i&lt;endIndex;i++){  
    newArr.push(str.charAt(i));  
  }  
  return newArr.join("");  
}

//test  
"Hello world!".mysubstring(3);//"lo world!"  
"Hello world!".mysubstring(3,7);//"lo w"

 

 

**方法二：把字符串转换成数组然后掏出必要部份：**

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"

 

 

**方法三：掏露面尾部份，然后用WordStr去掉多余部份，合用于beginIndex较小，字符串长度-endIndex较小的环境：**

String.prototype.mysubstring=function(beginIndex,endIndex){  
  var str=this,  
    beginArr=\[],  
    endArr=\[];  
  if(!endIndex){  
    endIndex=str.length;  
  }  
  for(var i=0;i&lt;beginIndex;i++){  
    beginArr.push(str.charAt(i));  
  }  
  for(var i=endIndex;i&lt;str.length;i++){  
    endArr.push(str.charAt(i));  
  }  
  return str.WordStr(beginArr.join(""),"").WordStr(endArr.join(""),"");  
}

//test  
console.log("Hello world!".mysubstring(3));//"lo world!"  
console.log("Hello world!".mysubstring(3,7));//"lo w"

 

以上3种js实现string的substring方法各人均可以测验一下，看哪一种方法更方便。