【js--字符串对象】

字符串对象

1、根据字符返回位置

方法名说明
indexOf()根据字符查找在字符串中第一次出现的位置的索引,若找不到则返回 - 1
lastindexOf根据字符查找在字符串中最后一次出现的位置的索引,如果找不到则返回 - 1

代码为

let str='hello,world'
       let a=str.indexOf('o')//输出值为4
       alert(a)
       let b=str.indexOf('a')//输出值为-1
       alert(b)
       let c=str.lastIndexOf('l')//输出值为9
       alert(c)
       let d=str.lastIndexOf('s')//输出值为-1
       alert(d)

2、根据位置返回字符

方法名说明
charAt()根据索引查找在字符串中的对应字符,如果找不到则返回空字符串
str[index]获取指定位置处字符

代码为:

let str='hello,world'
       console.log(str.charAt(5))//输出字符‘,’
       console.log(str[3])//输出字符l

3、字符串操作方法

3.1substring(a,b)和substr(起始索引,截取个数)

(substring)截取两个索引之间的所有字符,从a的字符开始截取,不包括b的字符 ,左闭右开区间

 let str='hello,world'
        // 截取字符串索引在[1,3)之间的所有字符
        let a=str.substring(1,3)
        // 输出值为el
        alert(a)

(substr) 从起始索引开始,往后截取字符

 let str='hello,world'
        // 从索引为2的字符开始往后截取5个字符
        let a=str.substr(2,5)
        //输出值为 llo,w
        alert(a)
        

3.2将字符串所有字符转换成大小写(toUpperCase,toLowerCase)

toUpperCase()将所有字符转换为大写形式

let str='hello,world'
        // 将所有字符转变为大写
        let  a=str.toUpperCase();
        // 输出值为HELLO,WORLD
        alert(a)

toLowerCase()将所有字符转换为小写形式

 let str='HELLO,WORLD'
        // 将所有字符转变为小写
        let  a=str.toLowerCase();
        // 输出值为hello,world
        alert(a)

3.3判断字符串是否含有某一字符

startsWith () 判断字符串是否以什么字符开头,是返回true,否则返回false

let str='hello,world'
        // 判断字符串是否以h开头
        let a=str.startsWith('h')
        // 字符串以h开头,输出true
        alert(a)
       

endsWith() 判断字符串是否以什么字符结尾,是返回true,不是返回false

let str='hello,world'
        // 判断字符串是否以d结尾
        let a=str.endsWith('d')
        // 字符串以d结尾,输出true
        alert(a)
       

includes() 判断字符串中是否包含某个字符,若包含返回true,不包含返回false

let str='hello,world'
        // 判断字符串中是否包含l
        let a=str.includes('l')
        // 字符串中包含l,输出true
        alert(a)

4.特殊字符串

4.1split()字符

将字符串根据指定的字符进行分割,拼成一个数组

 let str='hello,world'
        // 根据字符el对字符串进行分割
        let a=str.split('el')
        // 输出值为h,lo,world
        alert(a)

4.2replace(被替换的内容,替换的内容)

​ 将字符串中的部分字符进行替换

let str='hello,world'
        // 将字符串中的w替换为uu
        let a=str.replace('w','uu')
        // 输出值为hello,uuorld
        alert(a)
        

4.3trim()

去除字符串开头和末尾的空格

// 字符串前面有两个空格,末尾有三个空格
        let str='  hello,world   '
        // 输出整个字符串的长度(空格也算),输出值为16
        alert(str.length )
        // 去除开头和末尾的空格
        let a=str.trim()
        // 输出值为11
        alert(a.length )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值