Javscript字符串的常用方法有哪些?
# 是什么
从以下方面去理解:
- 操作方法
- 对字符串的增删改查
- 转换方法
- 转成别的数据类型
- 模板匹配方法
# 怎么用
# 操作方法
增
str不会变
let str = 'hello'
let result = str.concat(' world')
删
slice 到n个
substr 取n个
substring 到n个
slice和substring 类似, 区别在于第二个参数,后者会谁小谁在前面
let str = 'hello world'
console.log(str.slice(3)) // lo world
console.log(str.substr(3)) // lo world
console.log(str.substring(3)) // lo world
console.log(str.slice(3, 7)) // lo w
console.log(str.substr(3, 7)) // lo worl
console.log(str.substring(3, 7)) // lo w
改
- trim() trimLeft() trimRight()
- repeat()
- padStart padEnd()
- toLowerCase() toUpperCase()
- 对原字符串进行加工,不改变原值
let str = 'hello'
str.padStart(10, '.') // .....hello
str.padEnd(10,'.') // hello.....
查
- charAt() 下标从0 开始算
- indexOf() 下标从0 开始算
- startsWith() 是否以某某开始
- includes() 是否包含
let str = 'hello world'
str.charAt(5) // o
str.indexOf('h') // 0
str.startsWith('hi') // false
str.includes('world') // true
# 转换方法
- split
let str = 'hello world'
str.split(' ') // ['hello', 'world']
# 模板匹配方法
- replace() 替换元素
- match() 返回匹配数组
- search() 最早找到的位置n , 从下标0开始
let str = 'cat, bat, fat'
let reg = /.at/ig
let matches = str.match(reg) //[cat, bat, fat]
str.replace('at', 'oo') // "coo, bat, fat"
str.search('t') // 2
上次更新: 2021/12/19, 18:05:42