温馨提示×

js substring方法怎么使用

小亿
104
2023-07-27 10:20:40
栏目: 编程语言

substring() 方法用于提取字符串中指定位置的子字符串。

这个方法有两种使用方式:

1. 使用起始索引和结束索引: substring(startIndex, endIndex)

   - startIndex 表示要提取的子字符串的起始索引,包括此索引对应的字符。

   - endIndex(可选)表示要提取的子字符串的结束索引,但不包括此索引对应的字符。若不提供 endIndex 参数,则

会提取从 startIndex 到字符串末尾的所有字符。

2. 使用单个参数: substring(startIndex)

   - startIndex 表示要提取的子字符串的起始索引,包括此索引对应的字符。此时,会提取从 startIndex 到字符串末尾

的所有字符。

以下是一些使用 substring() 的示例:

javascript

const str = "Hello, World!";

console.log(str.substring(0, 5)); // 输出 "Hello"

console.log(str.substring(7)); // 输出 "World!"

请注意,substring() 方法不修改原始字符串,而是返回一个新的字符串作为提取结果。

0