JavaScript 中常用的字符串截取方法的列表,并按照 Markdown 格式生成:
-
substring(startIndex, endIndex)- 用途:返回指定索引范围内的子串。
- 示例:
const str = "Hello, World!"; const sub = str.substring(7, 12); console.log(sub); // 输出 "World"
-
substr(startIndex, length)- 用途:返回从指定索引开始指定长度的子串。
- 示例:
const str = "Hello, World!"; const sub = str.substr(7, 5); console.log(sub); // 输出 "World"
-
slice(startIndex, endIndex)- 用途:返回从指定索引开始到指定索引前的子串。
- 示例:
const str = "Hello, World!"; const sub = str.slice(7, 12); console.log(sub); // 输出 "World"
-
split(separator, limit)- 用途:将字符串拆分为数组,根据指定的分隔符进行分割。
- 示例:
const str = "Hello, World!"; const arr = str.split(", "); console.log(arr); // 输出 ["Hello", "World!"]
-
charAt(index)- 用途:返回指定索引位置处的字符。
- 示例:
const str = "Hello"; const char = str.charAt(1); console.log(char); // 输出 "e"
-
charCodeAt(index)- 用途:返回指定索引位置处字符的 Unicode 值。
- 示例:
const str = "Hello"; const code = str.charCodeAt(1); console.log(code); // 输出 101
-
startsWith(searchString, position)- 用途:判断字符串是否以指定的子串开头。可选参数
position表示从哪个索引位置开始搜索。 - 示例:
const str = "Hello, World!"; console.log(str.startsWith("Hello")); // 输出 true console.log(str.startsWith("World", 7)); // 输出 true
- 用途:判断字符串是否以指定的子串开头。可选参数
-
endsWith(searchString, length)- 用途:判断字符串是否以指定的子串结尾。可选参数
length表示在指定长度范围内搜索。 - 示例:
const str = "Hello, World!"; console.log(str.endsWith("!")); // 输出 true console.log(str.endsWith("World", 12)); // 输出 true
- 用途:判断字符串是否以指定的子串结尾。可选参数
-
indexOf(searchValue, startIndex)- 用途:返回指定子串在字符串中第一次出现的索引位置。
- 示例:
const str = "Hello, World!"; console.log(str.indexOf("o")); // 输出 4 console.log(str.indexOf("o", 5)); // 输出 8
-
lastIndexOf(searchValue, startIndex)- 用途:返回指定子串在字符串中最后一次出现的索引位置。
- 示例:
const str = "Hello, World!"; console.log(str.lastIndexOf("o")); // 输出 8 console.log(str.lastIndexOf("o", 7)); // 输出 4
-
match(regexp)- 用途:使用正则表达式匹配字符串,返回匹配结果数组。如果使用了全局标志(
g),将返回所有匹配项。 - 示例:
const str = "Hello, World!"; console.log(str.match(/o/g)); // 输出 ["o", "o"] console.log(str.match(/o/)); // 输出 ["o"]
- 用途:使用正则表达式匹配字符串,返回匹配结果数组。如果使用了全局标志(
-
replace(searchValue, replaceValue)- 用途:使用指定的字符串或正则表达式替换字符串中的匹配项。
- 示例:
const str = "Hello, World!"; const newStr = str.replace("o", "x"); console.log(newStr); // 输出 "Hellx, World!"
-
concat(string1, string2, ..., stringN)- 用途:连接两个或多个字符串,并返回新的字符串。
- 示例:
const str1 = "Hello"; const str2 = "World"; const newStr = str1.concat(", ", str2); console.log(newStr); // 输出 "Hello, World"