目录
1. length
获取字符串的长度。
var str = "Hello, World!"; console.log(str.length); // 输出 13
2. toUpperCase()
将字符串中的所有字母转换为大写。
var str = "hello"; console.log(str.toUpperCase()); // 输出 "HELLO"
3. toLowerCase()
将字符串中的所有字母转换为小写。:
var str = "HELLO"; console.log(str.toLowerCase()); // 输出 "hello"
4. trim()
移除字符串两端的空白字符(空格、换行、制表符等)
var str = " Hello World! "; console.log(str.trim()); // 输出 "Hello World!"
5. charAt()
返回指定位置的字符。
var str = "Hello"; console.log(str.charAt(1));
6. indexOf()
查找指定子字符串在字符串中首次出现的位置,如果未找到返回 -1。
var str = "Hello, World!"; console.log(str.indexOf("World")); // 输出 7
7. lastIndexOf()
查找指定子字符串在字符串中最后一次出现的位置。
var str = "Hello, Hello, World!"; console.log(str.lastIndexOf("Hello")); // 输出 7
8. slice()
提取字符串的一部分,返回一个新的字符串,原字符串不变。
var str = "Hello, World!"; console.log(str.slice(0, 5)); // 输出 "Hello"
9. substring()
提取字符串的一部分,与 slice()
类似,但不能接受负数参数。
var str = "Hello, World!"; console.log(str.substring(0, 5)); // 输出 "Hello"
10. replace()
替换字符串中的某个子字符串或正则表达式匹配的内容
var str = "Hello, World!";
console.log(str.replace("World", "JavaScript"));
// 输出 "Hello, JavaScript!"
11. split()
将字符串分割为数组,依据指定的分隔符。
var str = "apple,banana,cherry";
console.log(str.split(","));
// 输出 ["apple", "banana", "cherry"]
12. includes()
检查字符串是否包含指定的子字符串,返回 true
或 false
var str = "Hello, World!";
console.log(str.includes("World"));
// 输出 true
13. startsWith()
检查字符串是否以指定的子字符串开头,返回 true
或 false
。
var str = "Hello, World!";
console.log(str.startsWith("Hello"));
// 输出 true
14. endsWith()
检查字符串是否以指定的子字符串结尾,返回 true
或 false
。
var str = "Hello, World!";
console.log(str.endsWith("World!"));
// 输出 true
15. repeat()
返回一个新的字符串,表示将原字符串重复指定次数。
var str = "Hello";
console.log(str.repeat(3));
// 输出 "HelloHelloHello"