js字符串对象属性和方法概述
1、.length----获取字符串长度;
var myString="JavaScript";console.log(myString.length); //10
2、concat----连接字符串生成新的字符串;
var s1="a";var s2="b";var s3="c";console.log(s1.concat(s2,s3)); //abcconsole.log(s1) //a
3、indexOf(str,fromIndex)----找到匹配项返回索引值,如果没找到返回-1;
常用方法:
var myString="JavaScript";console.log(myString.indexOf("v")); //2console.log(myString.indexOf("Script")); //4console.log(myString.indexOf("key")); //-1
完整的indexof用法:
表示从索引位置fromIndex开始查找,如果fromIndex省略,则表示默认从起始索引0开始查找; 若fromIndex为负,则从索引0开始查找。console.log(myString.indexOf("v",5)); //-1console.log(myString.indexOf("v",1)); //2
4、charAt(index)----返回指定索引位置的字符,若索引越界,返回空字符串;
myString="JavaScript";console.log(myString.charAt(1)); //aconsole.log(myString.charAt(10000000000000000)); //若索引越界,返回空字符串 -- ""console.log(myString.charAt(-1)); //若索引越界,返回空字符串 -- ""
5、substr(fromIndex,length)----从起始索引fromIndex开始截取长度length的字符串,获取的字符串包含索引值的开始位置的值,如果length长度不指定或者超过可截取的最大长度,则截取到结尾,如果起始索引fromIndex为负,则从右往左截取,-1表示倒数第一个;
myString="JavaScript";console.log(myString.substr(1,1)); //a console.log(myString.substr(1,2)); //avconsole.log(myString.substr(1)); //avaScriptconsole.log(myString.substr(1,4000000)); //avaScriptconsole.log(myString.substr(-1,1)); //t console.log(myString.substr(-2,1)); //p console.log(myString.substr(-6,2)); //Sc console.log(myString.substr(-6,6)); //Script
6、substring(startIndex,endIndex)----截取 起始索引startIndex 到 结束索引endIndex的子字符串,结果包含startIndex处的字符,不包含endIndex处的字符,如果省略endIndex,则截取到结尾,若startIndex或者endIndex为负,则会被替换为0,若startIndex = endIndex,则返回空字符串,若startIndex > endIndex,则执行方法时,两个值会被交换;
myString="JavaScript";console.log(myString.substring(1,3)); //avconsole.log(myString.substring(4)); //Scriptconsole.log(myString.substring(-1,1)); //Jconsole.log(myString.substring(3,3)); //返回空console.log(myString.substring(3,1)); //等价于myString.substring(1,3)
7、slice(startIndex,endIndex)----截取 起始索引startIndex 到 结束索引endIndex的子字符串, 结果包含startIndex处的字符,不包含endIndex处的字符,基本用法和substring用法一样;
不同点:myString="JavaScript";console.log(myString.slice(1,3)) //av如果startIndex > endIndex,则执行方法时返回空字符串如果 start 为负,将它作为 length + start处理,此处 length 为数组的长度;console.log(myString.slice(-1,3)) //返回空如果 end 为负,就将它作为 length + end 处理,此处 length 为数组的长度;console.log(myString.slice(2,-3)) //vaScr
8、split()----字符串分割成数组,返回新数组,不影响原字符串;
var s="a,bc,d";console.log(s.split(",")); //["a", "bc", "d"]s="a1b1c1d1";console.log(s.split("1")); //["a", "b", "c", "d", ""]
9、join()----使用选择的分隔符将一个数组合并为一个字符串;
var myList=new Array("jpg","bmp","gif","ico","png");var imgString=myList.join("|"); console.log(imgString) //jpg|bmp|gif|ico|png
9、toLowerCase/toUpperCase----字符串大小写转换;
myString="JavaScript";console.log(myString.toLowerCase()) //javascriptconsole.log(myString.toUpperCase()) //JAVASCRIPT
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。