JavaScript的substring()方法用于提取字符串中指定开始索引和结束索引之间的字符子串。
语法:string.substring(startIndex, endIndex)
参数说明:
-
startIndex:必需,表示提取子串的开始索引位置。如果是负数,则将其作为字符串长度加上startIndex处理。
-
endIndex:可选,表示提取子串的结束索引位置,但不包括该位置的字符。如果省略该参数,则将提取从startIndex开始到字符串末尾的所有字符。如果是负数,则将其作为字符串长度加上endIndex处理。
返回值:返回提取的字符子串。
示例:
let str = "Hello, World!"; let substr1 = str.substring(7); // 从索引为7的位置开始提取,结果为"World!" let substr2 = str.substring(7, 12); // 从索引为7到索引为11之间的位置提取,结果为"World"
注意:
-
如果startIndex和endIndex相等,则返回空字符串。
-
如果startIndex大于endIndex,则会自动交换两个参数的值,相当于调换了起始位置和结束位置。
-
substring()方法不会改变原字符串,而是返回一个新的子串。