typescript 截取字符串
时间: 2023-10-20 10:34:58 浏览: 46
在TypeScript中,截取字符串可以使用字符串的`slice()`方法或者`substring()`方法。这两个方法都可以接收起始位置和结束位置作为参数,用于截取字符串的一部分。
使用`slice()`方法截取字符串的语法如下:
```
let str: string = "typescript";
let substr: string = str.slice(startIndex, endIndex);
```
其中,`startIndex`是截取的起始位置的索引,`endIndex`是截取的结束位置的索引(不包含在截取的结果中)。如果省略`endIndex`参数,则截取到字符串的末尾。
使用`substring()`方法截取字符串的语法如下:
```
let str: string = "typescript";
let substr: string = str.substring(startIndex, endIndex);
```
同样,`startIndex`是截取的起始位置的索引,`endIndex`是截取的结束位置的索引(不包含在截取的结果中)。如果省略`endIndex`参数,则截取到字符串的末尾。
请注意,这两个方法都会返回一个新的字符串,而不会修改原始字符串。另外,它们都可以使用负数的索引来表示从字符串的末尾开始的位置。
例如,如果我们想要截取"typescript"中的"script"部分,可以使用以下代码:
```
let str: string = "typescript";
let substr: string = str.slice(4, 9);
```
或者
```
let str: string = "typescript";
let substr: string = str.substring(4, 9);
```
以上两种方法都将返回"script"作为结果。
希望能帮到你!<span class="em">1</span><span class="em">2</span><span class="em">3</span><span class="em">4</span>