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