JavaScript 的 String
对象包含了许多用于操作字符串的方法。以下是一些常用 String
方法的详细介绍和示例代码。
常用 String 方法
charAt():
返回指定位置的字符。let greeting = "Hello, world!"; let char = greeting.charAt(7); // "w"
charCodeAt():
返回指定位置的字符的 Unicode 编码。let greeting = "Hello, world!"; let code = greeting.charCodeAt(7); // 119 ("w" 的 Unicode 编码)
concat():
连接两个或多个字符串。let part1 = "Hello"; let part2 = "World"; let result = part1.concat(", ", part2, "!"); // "Hello, World!"
endsWith():
判断字符串是否以指定的子字符串结尾。let greeting = "Hello, world!"; let endsWithExclamation = greeting.endsWith("!"); // true
fromCharCode():
将 Unicode 编码转为字符。let str = String.fromCharCode(72, 101, 108, 108, 111); // "Hello"
indexOf():
返回字符串中子字符串首次出现的位置。let greeting = "Hello, world!"; let index = greeting.indexOf("world"); // 7
includes():
检查字符串是否包含指定的子字符串。let greeting = "Hello, world!"; let includesWorld = greeting.includes("world"); // true
lastIndexOf():
从后向前搜索字符串,返回字符串最后出现的位置。let greeting = "Hello, world! Hello, moon!"; let lastIndex = greeting.lastIndexOf("world"); // 7
match():
查找字符串中与正则表达式匹配的部分。let greeting = "Hello, world!"; let matches = greeting.match(/(world)/); // ["world", index: 7, input: "Hello, world!", groups: undefined]
repeat():
将字符串复制指定次数。let str = "abc"; let repeated = str.repeat(3); // "abcabcabc"
replace():
替换字符串中与正则表达式匹配的子串。let greeting = "Hello, world!"; let replaced = greeting.replace("world", "everyone"); // "Hello, everyone!"
replaceAll():
替换字符串中所有与正则表达式匹配的子串。let greeting = "Hello, world! world!"; let replacedAll = greeting.replaceAll("world", "everyone"); // "Hello, everyone! everyone!"
search():
查找与正则表达式匹配的值。let greeting = "Hello, world!"; let found = greeting.search(/w/); // 7
slice():
提取字符串的片断。let greeting = "Hello, world!"; let part = greeting.slice(7, 12); // "world"
split():
把字符串分割为字符串数组。let [firstName, lastName] = "John Doe".split(" "); // firstName = "John", lastName = "Doe"
startsWith():
判断字符串是否以指定的子字符串开头。let greeting = "Hello, world!"; let startsWithHello = greeting.startsWith("Hello"); // true
substr():
从起始索引号提取字符串中指定数目的字符。let greeting = "Hello, world!"; let part = greeting.substr(7, 5); // "world"
substring():
提取字符串中两个指定的索引号之间的字符。let greeting = "Hello, world!"; let part = greeting.substring(7, 12); // "world"
toLowerCase():
把字符串转换为小写。let greeting = "Hello, World!"; let lower = greeting.toLowerCase(); // "hello, world!"
toUpperCase():
把字符串转换为大写。let greeting = "Hello, world!"; let upper = greeting.toUpperCase(); // "HELLO, WORLD!"
trim():
去除字符串两边的空白。let greeting = " Hello, world! "; let trimmed = greeting.trim(); // "Hello, world!"
toLocaleLowerCase():
根据本地主机的语言环境把字符串转换为小写。**toLocaleUpp