substring()
是 JavaScript 中的一个字符串方法,用于提取字符串中的一部分字符,并返回一个新的字符串。以下是 substring()
方法的基础概念、优势、类型、应用场景以及常见问题的解答。
substring()
方法接受两个参数:
startIndex
(必需):要提取的子字符串的起始索引(包括该索引)。endIndex
(可选):要提取的子字符串的结束索引(不包括该索引)。如果省略,则提取到字符串末尾。substring()
方法返回一个新的字符串,不会修改原始字符串。
let str = "Hello, World!";
// 提取 "Hello"
let result1 = str.substring(0, 5);
console.log(result1); // 输出: Hello
// 提取 "World"
let result2 = str.substring(7);
console.log(result2); // 输出: World!
// 提取整个字符串
let result3 = str.substring(0);
console.log(result3); // 输出: Hello, World!
如果 startIndex
或 endIndex
超出了字符串的长度,substring()
方法会自动调整这些值。
let str = "Hello";
let result = str.substring(10, 20);
console.log(result); // 输出: 空字符串,因为索引超出范围
解决方法:在使用 substring()
方法之前,检查索引是否在有效范围内。
let str = "Hello";
let startIndex = 10;
let endIndex = 20;
if (startIndex < str.length && endIndex <= str.length) {
let result = str.substring(startIndex, endIndex);
console.log(result);
} else {
console.log("索引超出范围");
}
如果 startIndex
或 endIndex
是负数,substring()
方法会将其视为 0。
let str = "Hello";
let result = str.substring(-3, 2);
console.log(result); // 输出: He
解决方法:在使用 substring()
方法之前,确保索引是非负数。
let str = "Hello";
let startIndex = -3;
let endIndex = 2;
if (startIndex < 0) startIndex = 0;
if (endIndex < 0) endIndex = 0;
let result = str.substring(startIndex, endIndex);
console.log(result); // 输出: He
通过这些方法和注意事项,可以有效地使用 substring()
方法来处理字符串,并避免常见的错误。
领取专属 10元无门槛券
手把手带您无忧上云