js实现 substring
在 JavaScript 中实现 substring
JavaScript 提供了多种方法来截取字符串的一部分,其中 substring() 是最常用的方法之一。以下是几种常见的实现方式:
使用 substring() 方法
substring() 方法接受两个参数:起始索引和结束索引(可选)。返回从起始索引到结束索引之间的字符串,不包括结束索引处的字符。
const str = "Hello, World!";
const result = str.substring(0, 5); // 从索引 0 开始,到索引 5 结束(不包括 5)
console.log(result); // 输出 "Hello"
如果省略第二个参数,substring() 会从起始索引截取到字符串末尾。

const str = "Hello, World!";
const result = str.substring(7); // 从索引 7 开始到末尾
console.log(result); // 输出 "World!"
使用 slice() 方法
slice() 方法与 substring() 类似,但支持负数索引(从字符串末尾开始计算)。
const str = "Hello, World!";
const result = str.slice(0, 5); // 从索引 0 开始,到索引 5 结束
console.log(result); // 输出 "Hello"
负数索引示例:

const str = "Hello, World!";
const result = str.slice(-6, -1); // 从倒数第 6 个字符到倒数第 1 个字符
console.log(result); // 输出 "World"
使用 substr() 方法(已废弃)
substr() 方法接受起始索引和长度作为参数,但已被标记为废弃,不建议在新代码中使用。
const str = "Hello, World!";
const result = str.substr(7, 5); // 从索引 7 开始,截取 5 个字符
console.log(result); // 输出 "World"
使用正则表达式
如果需要更灵活的截取方式,可以使用正则表达式匹配字符串的一部分。
const str = "Hello, World!";
const result = str.match(/Hello/)[0]; // 匹配 "Hello"
console.log(result); // 输出 "Hello"
手动实现 substring()
如果需要手动实现类似 substring() 的功能,可以通过循环或数组操作实现。
function customSubstring(str, start, end) {
if (end === undefined) end = str.length;
let result = "";
for (let i = start; i < end && i < str.length; i++) {
result += str[i];
}
return result;
}
const str = "Hello, World!";
const result = customSubstring(str, 0, 5);
console.log(result); // 输出 "Hello"
注意事项
substring()和slice()的主要区别在于对负数的处理:slice()支持负数索引,而substring()会将负数视为 0。- 如果起始索引大于结束索引,
substring()会自动交换参数,而slice()会返回空字符串。 - 在现代 JavaScript 中,推荐使用
substring()或slice(),避免使用已废弃的substr()。






