目录
6 indexOf 方法用于查找字符串中某个字符或子字符串的索引位置
7 lastIndexOf 方法用于查找字符串中某个字符或子字符串的最后一次出现的索引位置
8 includes 方法用于检查字符串是否包含指定的子字符串
9 startsWith 方法用于检查字符串是否以指定的子字符串开头
10 endsWith 方法用于检查字符串是否以指定的子字符串结尾
12 match 方法用于在字符串中查找匹配正则表达式的结果。返回一个数组,其中包含所有匹配的结果。如果没有匹配的结果,则返回null
13 replace 方法用于在字符串中替换指定子字符串。返回替换后的字符串
14 substring 方法用于从字符串中提取子字符串。返回被提取的子字符串
15 charAt 方法用于获取指定索引位置的字符。返回该索引位置的字符
16 concat 方法用于连接两个或多个字符串。返回连接后的字符串
1 length 方法用于获取字符串的长度
const str = 'hello'
console.log(str.length) // 输出:5
2 split 方法用于将字符串分割为子字符串数组
const str2 = 'apple,banana,orange'
console.log(str2.split(',')) // 输出:["apple", "banana", "orange"]
3 toLowerCase 方法用于将字符串转换为小写
const str3 = 'Hello World'
console.log(str3.toLowerCase()) // 输出:hello world
4 toUpperCase 方法用于将字符串转换为大写
const str4 = 'hello world'
console.log(str4.toUpperCase()) // 输出:HELLO WORLD
5 trim 方法用于去除字符串两端的空格
const str5 = ' hello world '
console.log(str5.trim()) // 输出:hello world
6 indexOf 方法用于查找字符串中某个字符或子字符串的索引位置
// 语法:
// indexOf(searchElement)
// indexOf(searchElement, fromIndex)
const str6 = 'hello world'
console.log(str6.indexOf('o')) // 输出:4
console.log(str6.indexOf('o', 6)) // 输出:7
console.log(str6.indexOf('o', 10)) // 输出:-1
7 lastIndexOf 方法用于查找字符串中某个字符或子字符串的最后一次出现的索引位置
该方法从
fromIndex
开始向前(左)搜索数组。但是数组中元素的位置先后还是按照从左往右的。
// 语法:
// lastIndexOf(searchElement)
// lastIndexOf(searchElement, fromIndex)
const str7 = 'hello oorld'
console.log(str7.lastIndexOf('o')) // 输出:7
console.log(str7.lastIndexOf('o', 6)) // 输出:6
console.log(str7.lastIndexOf('o', 10)) // 输出:7
8 includes 方法用于检查字符串是否包含指定的子字符串
const str8 = 'hello world'
console.log(str8.includes('world')) // 输出:true
console.log(str8.includes('world', 6)) // 输出:false
9 startsWith 方法用于检查字符串是否以指定的子字符串开头
const str9 = 'hello world'
console.log(str9.startsWith('hello')) // 输出:true
console.log(str9.startsWith('world')) // 输出:false
10 endsWith 方法用于检查字符串是否以指定的子字符串结尾
const str10 = 'hello world'
console.log(str10.endsWith('world')) // 输出:true
11 repeat 方法用于将字符串重复指定的次数
const str11 = 'hello'
console.log(str11.repeat(3)) // 输出:hellohellohello
12 match 方法用于在字符串中查找匹配正则表达式的结果。返回一个数组,其中包含所有匹配的结果。如果没有匹配的结果,则返回null
const str12 = 'hello world'
console.log(str12.match(/o/g)) // 输出:["o", "o"]
console.log(str12.match(/a/g)) // 输出:null
13 replace 方法用于在字符串中替换指定子字符串。返回替换后的字符串
const str13 = 'hello world'
console.log(str13.replace('world', 'universe')) // 输出:hello universe
14 substring 方法用于从字符串中提取子字符串。返回被提取的子字符串
// 语法:
// substring(第一个参数是起始索引 [, 第二个参数是结束索引(不包含)]) 第二个参数省略,默认截取到最后
const str14 = 'hello world'
console.log(str14.substring(0, 4)) // 输出:hell
console.log(str14.substring(1, 3)) // 输出: el
15 charAt 方法用于获取指定索引位置的字符。返回该索引位置的字符
const str15 = 'hello world'
console.log(str15.charAt(7)) // 输出:o
16 concat 方法用于连接两个或多个字符串。返回连接后的字符串
const str16 = 'hello'
const str17 = 'world'
console.log(str16.concat(' ', str17)) // 输出:hello world
console.log(str16.concat('+', str17)) // 输出:hello+world
// concat中的第一个参数是连接符