js中substr和substring
时间: 2024-06-08 15:12:34 浏览: 16
在JavaScript中,`substr`和`substring`都是用来截取字符串的方法,但它们有一些细微的区别。
1. `substr(startIndex, length)`:这个方法从指定的`startIndex`开始,截取指定长度为`length`的字符串。其中,`startIndex`表示起始位置的索引,如果为负数,则从字符串末尾开始计算;`length`表示要截取的长度。如果省略`length`参数,则截取到字符串末尾。
示例:
```javascript
const str = 'Hello, World!';
const result = str.substr(7, 5);
console.log(result); // 输出 "World"
```
2. `substring(startIndex, endIndex)`:这个方法从指定的`startIndex`开始,截取到指定的`endIndex`之前的字符串(不包含`endIndex`位置的字符)。其中,`startIndex`表示起始位置的索引,如果为负数,则从0开始计算;`endIndex`表示结束位置的索引,如果省略该参数,则截取到字符串末尾。
示例:
```javascript
const str = 'Hello, World!';
const result = str.substring(7, 12);
console.log(result); // 输出 "World"
```
需要注意的是,如果`startIndex`大于`endIndex`时,`substring`会自动交换这两个参数,并按正确的顺序进行截取。
另外,需要注意的是,这两个方法都返回一个新的字符串,原始字符串不会被修改。