js实现 substring
实现 substring 的方法
在 JavaScript 中,可以通过多种方式实现字符串的子串提取。以下是几种常见的方法:
使用 substring() 方法substring() 方法返回字符串中指定索引之间的字符,语法如下:
str.substring(startIndex, endIndex)
startIndex 是起始索引(包含),endIndex 是结束索引(不包含)。如果省略 endIndex,则提取到字符串末尾。
示例:
const str = "Hello, world!";
const result = str.substring(0, 5); // 返回 "Hello"
使用 substr() 方法substr() 方法从指定位置开始提取指定长度的字符,语法如下:
str.substr(startIndex, length)
startIndex 是起始索引,length 是要提取的字符数。如果省略 length,则提取到字符串末尾。
示例:
const str = "Hello, world!";
const result = substr(7, 5); // 返回 "world"
使用 slice() 方法slice() 方法与 substring() 类似,但支持负数索引(从末尾开始计算),语法如下:
str.slice(startIndex, endIndex)
如果参数为负数,则表示从字符串末尾开始计算。
示例:
const str = "Hello, world!";
const result = str.slice(-6, -1); // 返回 "world"
使用正则表达式提取子串
如果需要基于模式匹配提取子串,可以使用 match() 方法配合正则表达式。
示例:

const str = "Hello, world!";
const result = str.match(/world/)[0]; // 返回 "world"
注意事项
substring()和slice()的主要区别在于对负数的处理:substring()会将负数视为 0,而slice()支持负数索引。substr()方法已被标记为废弃,建议使用substring()或slice()替代。- 如果起始索引大于结束索引,
substring()会自动交换参数,而slice()会返回空字符串。






