1. indexOf()
返回字符串中指定文本首次出现的索引位置
let str = 'abcd'
let res = str.indexOf('cd')
console.log(res) // 打印匹配到的索引位置 2
// 如果没有符合的返回 -1 如果一次匹配多个字段,例如这个例子,返回第一个字符所在的索引
let str = 'abcd'
let res = str.indexOf('c',2) //它也可以接收第二个参数,指匹配开始的位置
console.log(res) // 2
2. lastIndexOf()
从后往前查找,返回字符串中指定文本首次出现的索引位置
let str = 'abcd'
let res = str.lastIndexOf('c') // 2
3. search()
搜索特定值的字符串,并返回匹配的位置
提示:
indexOf() 与 search()用法相似。但区别在于:
- search() 方法无法设置第二个开始位置参数。
- indexOf() 方法无法设置更强大的搜索值(例如将正则表达式)
let str = "abcd";
let res = str.search("c");
console.log(res); // 打印结果为2
//匹配不到时返回-1
4. slice()
提取字符串的某个部分并在新字符串中返回被提取的部分
// 该方法设置两个参数:起始索引(开始位置),终止索引(结束位置)。
// 如果某个参数为负,则从字符串的结尾开始计数。
// 如果省略第二个参数,则该方法将裁剪字符串的剩余部分:
let str = 'abcd'
let res = str.slice(0,2)
console.log(res) // 打印结果 ab 取不到结束位置的字符
5. substring()
截取字符串
// 方法等同于slice()方法,唯一的区别,这个参数不能为负数
let str = 'abcd'
let res = str.substring(2) // cd
6. substr()
截取字符串
// 用法还是等同于slice 唯一的区别 这里第二个参数指截取的字符长度
let str = 'abcd'
let res = str.substr(0,3)
console.log(res) //打印结果为abc
7. replace()
用另一个值替换在字符串中指定的值
// 他接收两个参数,第一个需要替换的值, 第二个替换后的值
// 如果没有匹配到要替换的值,返回原字符串
let str = 'abcd'
let res = str.replace('ab',3)
console.log(res) //打印结果 3cd
// 默认地,replace() 对大小写敏感。如需执行大小写不敏感的替换,请使用正则表达式 /i(大小写不敏感):
let res = str.replace(/AB/i,3)
console.log(res) //打印结果 3cd
8. toUpperCase()
把字符串转换为大写
let str = 'abcd'
let res = str.toUpperCase()
console.log(res) //打印结果: ABCD
9. toLowerCase()
把字符串转换为小写
let str = 'ABCD'
let res = str.toUpperCase()
console.log(res) //打印结果: abcd
10. concat()
连接两个或多个字符串
let str1 = 'abcd'
let str2 = '1234'
let res = str1.concat(str2) // 这里也可以这样写: let res = str1.concat('',str2)
console.log(res) // 打印结果: abcd1234
11. trim()
删除字符串两端的空白符
let str = ' ab cd '
let res = str.trim()
console.log(res) //打印结果: ab cd
//注意只能去除两边的空格,不能去除中间的
12. charAt()
返回字符串中指定下标的字符串
let str = 'abcd'
let res = str.charAt(1)
console.log(res) // 打印结果 b
//如果没有指定索引的字符,返回 ""
13. split()
将字符串转换为数组
// 如果()没有内容,就是将整个字符串作为数组的一项
let str = 'abcd'
let res = str.split()
console.log(res) //打印结果: ['abcd']
//如果是(""),就是将整个字符串的每一个字符作为数组的每一项
let str = 'abcd'
let res = str.split('')
console.log(res) //打印结果: ["a", "b", "c", "d"]
// 如果是(",")或者其他字符,就是将整个字符串以这个字符为分隔,分隔成数组的每一项
let str = 'ab,c,d'
let res = str.split(',')
console.log(res) //打印结果: ["ab", "c", "d"]
14. charCodeAt()
返回在指定的位置的字符的 Unicode 编码
var str="abc"
console.log(str.charCodeAt(1)) // 98
15. match()
在字符串内检索指定的值,该方法类似indexOf(),但是它返回指定的值,而不是字符串的位置。
var str="1 abc 2 def 3"
console.log(str.match(/\d+/g)) // ['1', '2', '3']
16. startsWith()
在字符串的起始部分检测到指定文本
let str="Hello world!";
console.log(str.startsWith("Hello")) // true
console.log(str.startsWith("o")) // false
console.log(str.startsWith("o",4)); // true //第二个参数, 匹配开始位置
17. endsWith()
在字符串的结束部分检测到指定文本
let str="Hello world!";
console.log(str.endsWith("!"))//true
console.log(str.endsWith("world!"))//true
console.log(str.endsWith("o",8));//true