string.slice()
时间: 2024-05-05 15:15:46 浏览: 15
The `slice()` method in JavaScript is used to extract a section of a string and return it as a new string. It takes two arguments: the start index and the end index of the section to be extracted.
Syntax:
```javascript
string.slice(startIndex, endIndex)
```
Parameters:
- `startIndex`: The index at which the extraction should start. If negative, it is treated as the length of the string plus the index.
- `endIndex`: The index at which the extraction should end. If omitted or greater than the length of the string, it extracts to the end of the string. If negative, it is treated as the length of the string plus the index.
Return Value:
A new string that contains the extracted section.
Example:
```javascript
const str = "Hello World";
const subStr = str.slice(0, 5);
console.log(subStr); // Output: "Hello"
```
In the above example, the `slice()` method extracts the characters from index 0 to index 4 (inclusive) of the string "Hello World" and returns a new string "Hello".
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)