字符串中常用的方法

来源:互联网 发布:辣木籽退伍军人淘宝 编辑:程序博客网 时间:2024/06/05 22:47

一、charAt()
获取对于下标的字符
返回值:获取到的字符,没有对应的下标返回空的字符串

var str = 'ni hai ji den na tian ma';            //alert(str.length)//24            alert(str.charAt(1))            //返回i 不写默认为0//返回空 因为对应坐标是空格

二、charCodeAt()
获取对应下标处字符的编码
返回值:获取到的字符编码(0~65535),没有对应下标的返回NaN

      var str = 'Do you remember me?'            alert(str.charCodeAt(0))            //查找字符的编码 68

三、String.fromCharCode()
将字符编码转成相对应的字符
alert(String.fromCharCode(68)) //返回D 根据字符编码 返回相应的字符

四、字符串大小写转换
toLowerCase 全部转成小写
toUpperCase 全部转成大写
以返回值的形式得到结果,原字符串不会改变

var str = 'Your figure is dimly gone'            alert(str.toLowerCase())        //返回 your figure is dimly gone            alert(str.toUpperCase())        //返回 YOUR FIGURE IS DIMLY GONE

五、判断是否相等
== 和 === 运算符
一般js中判断相不相等,都是用” == ” 和 ” === ”
== 是值相等
=== 是值、类型相等
字符串与数字比大小是数字与数字的比较
字符串与字符串之间比较的是首字符的编码

var str4 = 1;var str5 = "1";console.log(str4==str5);// trueconsole.log(str4===str5);// falsealert('10'>9)//truealert('10'>'9')//false

六、查找字符串
indexOf()默认从左侧开始查找对应第一次出现的字符串的下标
lastIndexOf从右侧开始查找对应第一次出现的字符串的下标
如果找到了对应的元素则返回该元素的下标值,否则返回-1
第一个参数如果字符串中有重复的字符只会找第一个,就不会往下找了
第二个参数是从第几位开始找 不能为负数 找不到返回-1

var str = 'I do not understand where the most peace of mind';            alert(str.length)//48            alert(str.indexOf('o'))            //返回3 查找字符串里面首次出現的字符 找到就不往下找了            alert(str.lastIndexOf('d'))            //返回47 从右边往左边找首次出现的 下标还是从左往右

七、replace
从左侧开始查找对应的字符串,找到之后把它替换。
不会更改原来的字符串
注意:不会更改原来的字符串

var str = 'When the rain turned into light rendering the cicada';            alert(str.replace('the','THE'));            //返回When THE rain turned into light rendering the cicada            alert(str)            //返回When the rain turned into light rendering the cicada

八、提取字符串
substring提取字符串
第一个参数开始提取字符串的起始位置,如果第二个参数没写之间提取到末尾
第二个参数是到提取的终点位置(不包含)
如果任何一个参数小于0或者是NaN都会当作是0
如果第一个参数大于第二个参数就会前后自动颠倒
如果第二参数大于字符串的length,就会把他等于字符串的length

var str = 'If pride is not taken cold by the real sea';//从某个下标开始提取,一直到提取到原字符串的末尾       //alert(str.substring(2))//返回pride is not taken cold by the real sea//从参数1下标开始提取,一直提取到原字符串参数2下标之前   //alert(str.substring(2,16))//返回 pride is not 

substr:
从某个下标开始提取,一直到提取到原字符串的末尾
第一个参数是开始位置
第二个参数是提取的长度

var str = 'No more than half a day';            alert(str.substr(3));            //返回more than half a day            alert(str.substr(3,4))            //返回more  第二参数是提取几个长度的字符

九、切割 split()
切割字符串。成为数组
返回值:被切割后的字符串被保存在数组中然后返回
1.可以以字符串里面的内容为分隔符
2.split() 分割成一个数组
3.split(”)字符串中每个字符用逗号隔开分成多个数组

var str= 'Love and hate change from cold and warm';            //alert(str.split())            //返回['Love and hate change from cold and warm']            //alert(str.split().length)//1            //(str.split(''))            //返回[L,o,v,e, ,a,n,d, ,h,a,t,e, ,c,h,a,n,g,e, ,f,r,o,m, ,c,o,l,d, ,a,n,d, ,w,a,r,m]            //alert(str.split('').length)//39            alert(str.split('a'))            //返回[Love ,nd h,te ch,nge from cold ,nd w,rm]