substring()
是 JavaScript 中的一个字符串方法,用于提取字符串中介于两个指定下标之间的字符。这个方法返回一个新的字符串,这个字符串包含源字符串从 startIndex
开始(包括 startIndex
)到 endIndex
结束(不包括 endIndex
)的所有字符。
str.substring(indexStart[, indexEnd])
indexStart
必需,表示要提取的第一个字符的位置。indexEnd
可选,表示要提取的最后一个字符的位置的后一位。如果省略,则提取到字符串末尾。substring()
方法返回的是一个新的字符串类型。
let str = "Hello, World!";
let result1 = str.substring(0, 5); // 返回 "Hello"
let result2 = str.substring(7); // 返回 "World!"
console.log(result1); // 输出: Hello
console.log(result2); // 输出: World!
indexStart
大于 indexEnd
,substring()
会交换这两个参数的位置。NaN
,它会被当作 0
处理。substring()
不会抛出错误,而是会提取到字符串的末尾。indexStart
和 indexEnd
的顺序颠倒,可以使用 Math.min()
和 Math.max()
来确保正确的顺序。indexStart
和 indexEnd
的顺序颠倒,可以使用 Math.min()
和 Math.max()
来确保正确的顺序。通过上述方法,可以有效地使用 substring()
方法,并避免常见的错误。
领取专属 10元无门槛券
手把手带您无忧上云