20210602-JavaScript-字符串基本操作-查找截取

1、获取字符串长度 str.length

var str = 'hello world!how are you!';
console.log(str.length);

2、查找指定字符位置
2.1 IndexOf ()和 lastIndexOf()

var str = 'hello world!how are you!';
console.log(str.indexOf('how'))   // 查找how最早出现的位置,无则返回-1
console.log(str.indexOf('h',1))   // 1表示从1开始索引(包含位置1)
console.log(str.lastIndexOf('h'))  //查找h最后出现的位置,无则返回-1

2.2 search()

var str = 'hello world!how are you!';
console.log(str.search('o'))   //查找o最早出现的位置,无则返回-1

indexOf() 和 search()的区别:前者可以设置起始搜索位置后者不行;而后者可以使用正则表达式前者不行;

3、截取片段
3.1 slice()

var str = 'hello world!how are you!';
console.log(str.slice(1, 3))   //查找字符串str中位置1到3的字符,对应位置无结果则返回为空
console.log(str.slice(-3-1))    //查找倒数第3至倒数第1的字符
console.log(str.slice(5))   // 查找位置5至末尾的字符

3.2 substring()
跟slice()类似,但不支持反向位置查找且无返回为-1

3.3 substr()

var str = 'hello world!how are you!';
console.log(str.substr(1, 3))   //1指定开始查找位置,3指定查找长度
console.log(str.substr(-5, 3))    //支持反向位置查找

3.4 match()

var str = 'hello world!how are you!';
console.log(str.match('how'))   //查找how匹配的字符,返回【how】
rex = /\d/mg    //定义正则匹配公式,\d代表匹配数字,mg代表匹配全局多次
console.log(sms.match(rex))   // 查找对象中全部数字并返回(每次匹配结果单独返回在结果集中)

match() 和indexOf()都是查找指定字符(串),但前者是返回对应值,可以使用正则表达式查找特定特征的值

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值