JavaScript的substring()方法用于从字符串中提取指定范围的子字符串,并返回提取的子字符串。
它有两种使用方式:
- substring(startIndex, endIndex):提取从startIndex到endIndex之间的字符,不包括endIndex位置的字符。如果省略endIndex,则提取从startIndex到字符串末尾的所有字符。
例如:
let str = "Hello, World!"; let subStr = str.substring(0, 5); console.log(subStr); // 输出 "Hello"
- substring(startIndex):提取从startIndex到字符串末尾的所有字符。
例如:
let str = "Hello, World!"; let subStr = str.substring(7); console.log(subStr); // 输出 "World!"
需要注意的是,如果startIndex大于endIndex,则substring()方法会自动交换这两个参数的位置。
此外,substring()方法不会修改原始字符串,而是返回一个新的字符串。