最近难得抽空摸鱼,把工作开发中常见的容易混淆的字符串操作方法做一些概括,主要介绍slicesubstringsubstrsubstrsplitjoinStringtoString等方法,这些方法不会改变原字符串,更多字符操作方法请看菜鸟教程。?传送门1.slice方法返回一个索引和另一个索引之间的字符串str.slice(beginIndex[,endIndex])基本用法varstr="1234567890";console.log(str.length)//10//截取第一个字符串console.log(arr.slice(0,1))//1如果beginIndex为负数,则将该值加到前面字符串的长度上计算(如果字符串的长度加起来还是负数,则从0开始截取)//这两个是等价的console.log(str.slice(7,10));//890console.log(str.slice(-3,10));//890如果省略endIndex,slice()字符被提取到字符串的末尾。//这两个是等价的console.log(str.slice(7,10));//890console.log(str.slice(7));//890//拦截最后一个字符串控制台。日志(str.slice(-1));//0slice数组操作类似于字符串操作。需要特别说明的是,该方法可以将类数组对象转换为数组。//将arguments转为数组,类似Es6中的Array.from方法Array.prototype.slice.call(arguments)2.substring方法返回字符串str.substring(indexStart,[indexEnd])整体方法类似slice方法,但需要注意以下六点:如果省略indexEnd,则将substring()字符提取到字符串的末尾。//这两个是等价的console.log(str.substring(7))//890console.log(str.substring(7,10))//890如果任何参数小于0或NaN,则认为是0.//这三个也是等价的str.substring(0,1)//1str.substring(-1,1)//1str.substring(NaN,1)//如果任何参数大于stringName则为1.length被认为是stringName.length。//这两个也是等价的str.substring(7,10)//890str.substring(7,11)//890如果indexStart大于indexEnd,那么substring()的效果就好像两个参数被交换了一样;//这两个也是等价的str.substring(1,0)//1str.substring(0,1)//1如果indexStart等于indexEnd,substring()返回一个空字符串。3、substr方法返回从指定索引开始的字符串长度str.substring(start,[length])substring和substr的主要区别在于最后一个参数不同,前者是索引,后者是长度。注意以下三点:如果start为正且大于或等于字符串的长度,则substr()返回空字符串。如果start为负数,则将该值加上字符串长度再计算(如果加上字符串长度后还是负数,则从0开始截取)。`如果length为0或负数,substr()返回一个空字符串。如果省略length,substr()字符将被提取到字符串的末尾。4.split方法将一个字符串拆分成一个字符串数组。str.split(separator,limit)separator可选参数,字符串或正则表达式varstr="1234567890";console.log(str.split())//["1234567890"]console.log(str.split(''))//["1","2","3","4","5"","6","7","8","9","0"]//由/字符分隔varstrs="1/2/3/4/5/6/7/8/9/0";console.log(strs.split('/'))//["1","2","3","4","5","6","7","8","9","0"]limit可选参数,可指定返回数组的最大长度varstrs="1/2/3/4/5/6/7/8/9/0";//limti值为5,数组长度为5console.log(strs.split('/',5))//["1","2","3","4","5"]//不改变原来的数据console.log(strs)//["1/2/3/4/5/6/7/8/9/0"]5.join方法用于组合All元素成字符串str.join(separator)separator可选参数,可选。指定要使用的定界符。如果省略此参数,则使用逗号作为分隔符//join通常与split()一起使用varstr="1234567890";varstrs=str.split('/')//["1","2","3","4","5","6","7","8","9","0"]//实现分隔符的替换console.log(strs.join());//1,2,3,4,5,6,7,8,9,0console.log(strs.join('|'))//1|2|3|4|5|6|7|8|9|06.toString和String方法都将参数转换为字符类型字符串,但不能转换成字符串。toString方法可以将数组转换为字符串并返回结果。varfruits=["香蕉","橙子","苹果","芒果"];水果.toString();//输出香蕉、橙子、苹果、芒果
