Home  >  Article  >  Web Front-end  >  3种js实现string的substring方法_javascript技巧

3种js实现string的substring方法_javascript技巧

WBOY
WBOYOriginal
2016-05-16 15:33:041938browse

最近遇到一个题目,“如何利用javascript实现string的substring方法?”我目前想到的有以下三种方案:
方法一:用charAt取出截取部分:

String.prototype.mysubstring=function(beginIndex,endIndex){
  var str=this,
    newArr=[];
  if(!endIndex){
    endIndex=str.length;
  }
  for(var i=beginIndex;i

方法二:把字符串转换成数组然后取出需要部分:

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"


 方法三:取出头尾部分,然后用replace去掉多余部分,适用于beginIndex较小,字符串长度-endIndex较小的情况:

String.prototype.mysubstring=function(beginIndex,endIndex){
  var str=this,
    beginArr=[],
    endArr=[];
  if(!endIndex){
    endIndex=str.length;
  }
  for(var i=0;i

以上3种js实现string的substring方法大家都可以尝试一下,比较一下哪种方法更方便,希望本文对大家的学习有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn