typescript怎么获取字符串中部分信息
时间: 2024-04-30 09:21:49 浏览: 16
你可以使用字符串的一些内置方法来获取字符串中部分信息。以下是一些常见的方法:
1. `substring(startIndex: number, endIndex?: number)`:返回从指定起始位置到指定结束位置之间的子字符串。
```typescript
const str = "Hello, world!";
const substr = str.substring(7, 12); // "world"
```
2. `slice(startIndex: number, endIndex?: number)`:返回从指定起始位置到指定结束位置之间的子字符串,与 `substring()` 方法类似,但支持负数索引。
```typescript
const str = "Hello, world!";
const substr = str.slice(7, 12); // "world"
```
3. `substr(startIndex: number, length?: number)`:返回从指定起始位置开始,指定长度的子字符串。
```typescript
const str = "Hello, world!";
const substr = str.substr(7, 5); // "world"
```
4. `indexOf(searchValue: string, fromIndex?: number)`:返回指定字符串在原字符串中第一次出现的位置,从指定位置开始搜索。
```typescript
const str = "Hello, world!";
const index = str.indexOf("world"); // 7
```
5. `lastIndexOf(searchValue: string, fromIndex?: number)`:返回指定字符串在原字符串中最后一次出现的位置,从指定位置开始向前搜索。
```typescript
const str = "Hello, world!";
const index = str.lastIndexOf("l"); // 10
```
这些方法都返回子字符串,你可以将其存储在变量中,以便后续使用。