返回
探索字符串操作方法的异同:str.slice()、str.substring()、str.substr()
闲谈
2023-11-20 07:24:15
str.slice() 方法
str.slice() 方法用于从字符串中提取指定范围的字符。其语法如下:
str.slice(startIndex, endIndex)
- startIndex:指定要提取的第一个字符的索引位置。如果该值小于 0,则从字符串的末尾开始计数。
- endIndex:指定要提取的最后一个字符的索引位置。如果该值小于 0,则从字符串的末尾开始计数。
str.substring() 方法
str.substring() 方法也用于从字符串中提取指定范围的字符。其语法如下:
str.substring(startIndex, endIndex)
- startIndex:指定要提取的第一个字符的索引位置。如果该值小于 0,则从字符串的末尾开始计数。
- endIndex:指定要提取的最后一个字符的索引位置。如果该值小于 0,则从字符串的末尾开始计数。
str.substr() 方法
str.substr() 方法用于从字符串中提取指定范围的字符。其语法如下:
str.substr(startIndex, length)
- startIndex:指定要提取的第一个字符的索引位置。如果该值小于 0,则从字符串的末尾开始计数。
- length:指定要提取的字符的数量。如果该值小于 0,则从 startIndex 位置开始提取到字符串末尾的所有字符。
三者异同
-
相同点:
- 这三种方法都可以从字符串中提取指定范围的字符。
- 它们都接受两个参数:startIndex 和 endIndex。
- 它们都返回一个新的字符串。
-
不同点:
- str.slice() 方法对负值参数的处理与 str.substring() 和 str.substr() 方法不同。当 startIndex 或 endIndex 为负值时,str.slice() 方法会从字符串的末尾开始计数,而 str.substring() 和 str.substr() 方法会抛出异常。
- str.substr() 方法接受第二个参数 length,用于指定要提取的字符的数量,而 str.slice() 和 str.substring() 方法的第二个参数 endIndex 指定要提取的最后一个字符的索引位置。
- str.substr() 方法的第一个参数 startIndex 可以为负值,这使得它可以从字符串的指定位置开始提取字符,而 str.slice() 和 str.substring() 方法的第一个参数 startIndex 只接受非负值。
使用场景
- str.slice() 方法通常用于从字符串中提取指定范围的字符,并返回一个新的字符串。例如,以下代码从字符串 "Hello, world!" 中提取从索引位置 7 到索引位置 12 的字符,并返回 "world":
const str = "Hello, world!";
const newStr = str.slice(7, 12);
console.log(newStr); // "world"
- str.substring() 方法通常用于从字符串中提取指定范围的字符,并返回一个新的字符串。例如,以下代码从字符串 "Hello, world!" 中提取从索引位置 7 到索引位置 12 的字符,并返回 "world":
const str = "Hello, world!";
const newStr = str.substring(7, 12);
console.log(newStr); // "world"
- str.substr() 方法通常用于从字符串中提取指定范围的字符,并返回一个新的字符串。例如,以下代码从字符串 "Hello, world!" 中提取从索引位置 7 开始的 5 个字符,并返回 "world":
const str = "Hello, world!";
const newStr = str.substr(7, 5);
console.log(newStr); // "world"
总结
str.slice()、str.substring() 和 str.substr() 方法都是 JavaScript 中常用的字符串操作方法。它们都可以从字符串中提取指定范围的字符,但它们在某些方面存在差异。在实际项目中,您需要根据具体的需求选择合适的方法。