# JavaScript教程 - 13 字符串和正则表达式
下面介绍一下字符串常用的方法和在 JavaScript 中使用正则表达式对字符串进行处理。
# 13.1 字符串常用方法
方法有很多,先了解一下,开发的时候忘记了,可以来查看。
需要注意,字符串是不可变的,所以创建后就无法修改了,执行字符串的方法后,得到的都是一个新的字符串。
# 1 基本属性
.length
:获取字符串的长度
const str = 'hello';
console.log(str.length); // 输出: 5
1
2
2
# 2 查找类方法
字符串本质是一个字符数组,所以有很多方法和数组相似。
'hello' -> ['h', 'e', 'l', 'l', 'o']
1
所以字符串可以通过下标获取对应位置的字符。
举个栗子:
let str = 'hello';
console.log(str[0]); // h
console.log(str[1]); // e
1
2
3
2
3
- 能依次获取字符串中的字符。
你也可以使用 charAt(index)
,.charAt(index)
也是返回指定位置字符。
const str = 'hello';
console.log(str.charAt(1)); // 输出: 'e'
1
2
2
下面再介绍一下其他常用的方法。
.indexOf()
:返回子串在字符串中第一次出现的位置,找不到返回 -1
const str = 'hello';
console.log(str.indexOf('l')); // 输出: 2
1
2
2
.lastIndexOf()
:返回子串在字符串中最后一次出现的位置
const str = 'hello';
console.log(str.lastIndexOf('l')); // 输出: 3
1
2
2
.includes()
:判断是否包含某个子串,返回布尔值
const str = 'hello';
console.log(str.includes('el')); // 输出: true
1
2
2
.startsWith()
:判断是否以某个子串开头
const str = 'hello';
console.log(str.startsWith('he')); // 输出: true
1
2
2
.endsWith()
:判断是否以某个子串结尾
const str = 'hello';
console.log(str.endsWith('lo')); // 输出: true
1
2
2
# 3 截取类方法
.slice(start, end)
:截取start到end区间的字符,包含start、不包含end,支持负数。start
可以大于end
(结果是空字符串)。
const str = 'hello';
console.log(str.slice(1, 4)); // 输出: 'ell'
console.log(str.slice(-4, -1)); // 'ell'(-1表示从末尾开始)
1
2
3
2
3
.substring(start, end)
:截取start到end区间的字符,包含start、不包含end,不支持负数,如果start > end
,它会自动调换两个参数
const str = 'hello';
console.log(str.substring(1, 4)); // 输出: 'ell'
1
2
2
内容未完......
← 12-对象和数组补充 14-常用API-1 →