列举JavaScript字符串的一些常用方法并简要描述它们的用途。
1. **charAt(index)** - 返回字符串中指定位置的字符。
const str = "hello";
str.charAt(1); // "e"
2. **charCodeAt(index)** - 返回字符串指定位置字符的 Unicode 编码。
const str = "hello";
str.charCodeAt(1); // 101
3. **concat(str1, str2, ...)** - 将一个或多个字符串拼接到原字符串后,返回新字符串。
const str = "hello";
str.concat(" ", "world"); // "hello world"
4. **includes(substring, start)** - 检查字符串是否包含指定子字符串,返回布尔值。
const str = "hello world";
str.includes("world"); // true
5. **indexOf(substring, start)** - 返回指定子字符串在字符串中首次出现的索引;若不存在则返回 -1。
const str = "hello world";
str.indexOf("world"); // 6
6. **lastIndexOf(substring, start)** - 返回指定子字符串在字符串中最后一次出现的索引;若不存在则返回 -1。
const str = "hello world hello";
str.lastIndexOf("hello"); // 12
7. **slice(start, end)** - 提取字符串的子字符串,从 `start` 开始到 `end`(不包括 end)结束。
const str = "hello world";
str.slice(0, 5); // "hello"
8. **substring(start, end)** - 类似 `slice()`,但不接受负值,提取 `start` 到 `end` 之间的子字符串。
const str = "hello world";
str.substring(0, 5); // "hello"
9. **substr(start, length)** - 从 `start` 开始提取指定 `length` 个字符。
const str = "hello world";
str.substr(0, 5); // "hello"
10. **toLowerCase()** - 将字符串转换为小写。
const str = "Hello World";
str.toLowerCase(); // "hello world"
11. **toUpperCase()** - 将字符串转换为大写。
const str = "hello world";
str.toUpperCase(); // "HELLO WORLD"
12. **trim()** - 去除字符串首尾的空白字符。
const str = " hello world ";
str.trim(); // "hello world"
13. **replace(searchValue, newValue)** - 替换字符串中指定的子字符串(或正则表达式匹配的内容)。
const str = "hello world";
str.replace("world", "JavaScript"); // "hello JavaScript"
14. **replaceAll(searchValue, newValue)** - 替换所有匹配的子字符串(支持全局替换)。
const str = "hello world, world";
str.replaceAll("world", "JavaScript"); // "hello JavaScript, JavaScript"
15. **split(separator, limit)** - 按照指定分隔符将字符串拆分为数组。
const str = "hello world";
str.split(" "); // ["hello", "world"]
16. **startsWith(substring, start)** - 判断字符串是否以指定子字符串开头,返回布尔值。
const str = "hello world";
str.startsWith("hello"); // true
17. **endsWith(substring, length)** - 判断字符串是否以指定子字符串结尾,返回布尔值。
const str = "hello world";
str.endsWith("world"); // true
18. **match(regex)** - 使用正则表达式在字符串中查找匹配项,返回一个数组或 `null`。
const str = "hello world";
str.match(/world/); // ["world"]
19. **matchAll(regex)** - 返回一个迭代器,其中包含所有匹配项(支持全局和分组匹配)。
const str = "hello world";
Array.from(str.matchAll(/o/g)); // [["o"], ["o"]]
20. **padStart(targetLength, padString)** - 用指定字符串在开头填充字符串,直到达到目标长度。
const str = "5";
str.padStart(3, "0"); // "005"
21. **padEnd(targetLength, padString)** - 用指定字符串在结尾填充字符串,直到达到目标长度。
const str = "5";
str.padEnd(3, "0"); // "500"
这些方法可以用于字符串的查找、替换、格式化等各种操作,使字符串处理更加方便。