【JS】字符串的常用方法及slice/substr/substring的区别

🌿 总结JS中字符串的常用方法,以及容易混淆的substr、substring和slice之间的区别。


先准备一些测试字符串

const str1 = 'abc'
const str2 = '123'
const str = 'hello world'
const strA = 'Hello World'

(1)转换

1.toLocaleLowerCase()

字符串转小写

strA.toLowerCase() // hello world

2.toUpperCase()

转大写

str.toUpperCase() // HELLO WORLD

3.split(char)

根据符号char,将字符串转化成数组

const str3 = 'A B C'
const str4 = 'A-B-C'
console.log(str3.split(' ')); // ['A', 'B', 'C']
console.log(str4.split('-')); // ['A', 'B', 'C']

(2)查找

3.charAt(num)

找到指定位置的字符,下标从0开始

str.charAt(4) // o

4.charCodeAt(num)

找到指定位置字符的unicode编码

str.charCodeAt(4) // 111

5.indexOf(str)

返回指定字符串在目标字符串中第一次出现的位置下标,从0开始,没找到返回-1

str.indexOf('lo') // 3

6.lastIndexOf(str)

返回指定字符串在目标字符串中最后一次出现的位置下标

str.lastIndexOf('l') // 9

(3)截取

7.slice()

返回字符串中提取的子串

// 只有一个参数,为正数表示提取开始下标到结束的字符串
const res7 = str.slice(3) // lo world
// 只有一个参数,负数,表示提取从倒数第n位到结束的字符串,最后一位是-1
const res8 = str.slice(-3) // rld
// str.slice(n, m)两个参数,返回下标[n, m)之间的字符串,包含n,不包含m
const res9 = str.slice(3, 7) // lo w
// 起始下标大于结束下标,返回空串
const res10 = str.slice(7, 3) // 空串
// str.slice(-7, -3)两个都是负数,从后面开始截取[-7, -3)
const res11 = str.slice(-7, -3) // o wo
// 不传参数,返回源字符串
const res12 = str.slice() // hello world

8.substring()

与slice()的用法和返回结果一致,但是substring()不接受负数参数

// 与slice一致
const res13 = str.substring(3) // lo world
// 传负数会返回原字符串,substring不接受负数
const res14 = str.substring(-3) // hello world
// 与slice一致
const res15 = str.substring(3, 7) // lo w

9.substr()

// 传一个参数,表示提取指定下标到结束的字符串
const res16 = str.substr(3) // lo world
// str.substr(n, m) 两个参数,第一个n表示开始下标,m表示截取长度
const res17 = str.substr(3, 2) // lo
// 第二个参数超过字符串总长度,表示截取指定下标到结束的字符串
const res18 = str.substr(3, 12) // lo world
// 第一个参数位负数,表示从倒数第n位截取指定长度的字符串
const res19 = str.substr(-3, 2) // rl
// 第二个参数为负数,返回空串
const res20 = str.substr(-3, -2) // 空串


slice/substring/substr的区别:

1.slice(n, m) 截取[n, m)区间内的字符串,n和m可以为负数
2.substring(n, m) 截取[n, m)区间内的字符串,n和m不能为负数
3.substr(n, len) 截取从n为开始,长度为len的字符串,n可以为负

(3)替换

10.replace(reg, char)

第一个参数可以是字符串或者正则,将匹配的字符替换成第二个参数

// 第一个参数传字符串,只会替换第一个匹配到的字符
const res21 = str.replace('l', '') // helo world
// 第一个参数是正则,替换匹配到的所有字符
const res22 = str.replace(/l/ig, '*') // heo word

11.replaceAll

用法与replace一致,但是会替换所有匹配结果

const res23 = str.replaceAll('l', '*') // heo word

(4)匹配

12.match(reg)

// 传正则,返回所有匹配结果字符串
const res24 = str.match(/l/ig) // ['l', 'l', 'l']
// 传字符串,返回匹配结果信息
const res25 = str.match('ll') // ['ll', index: 2, input: 'hello world', groups: undefined]
const res26 = str.match('l') // ['ll', index: 2, input: 'hello world', groups: undefined]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值