TypeScript String(字符串)


TypeScript String(字符串)是 TypeScript 中的基本数据类型之一。它用于表示一系列字符,可以是单引号、双引号或反引号括起来的任何字符序列。字符串文字可以包含任意数量的Unicode字符。在 TypeScript 中,字符串一旦被定义,就不能再次被修改。

字符串的定义

有多种方式来定义 TypeScript 字符串:

单引号

let str1: string = 'hello, world';

双引号

let str2: string = "hello, TypeScript";

反引号

let str3: string = `hello, ${str1}`;

反引号可以用作模板字符串,它允许我们在字符串中插入表达式和变量。表达式和变量可以用${}包围,它们会被替换为相应的值。

字符串的属性和方法

在 TypeScript 中,String 类提供了一些属性和方法,让我们可以操作字符串。

属性

  1. length:获取字符串的长度
const str: string = "hello";
console.log(str.length);  // 5

方法

  1. charAt(index: number):获取字符串中指定位置的字符
const str: string = "hello";
console.log(str.charAt(0));  // "h"
  1. concat(str1: string, str2: string, …, strX: string):将两个或多个字符拼接成一个新的字符串
const str: string = "hello";
console.log(str.concat(", ", "world"));  // "hello, world"
  1. indexOf(searchValue: string, fromIndex?: number):在字符串中查找指定的子字符串,并返回它的位置。如果找到了,返回子字符串的起始位置;否则返回-1,如果未提供 fromIndex,则从索引 0 开始查找。
const str: string = "hello world";
console.log(str.indexOf("world"));  // 6
console.log(str.indexOf("World"));  // -1
  1. lastIndexOf(searchValue: string, fromIndex?: number):与indexOf方法类似,不过是从字符串的末尾(从右向左)开始查找。
const str: string = "hello world";
console.log(str.lastIndexOf("o"));  // 7
  1. slice(startIndex: number, endIndex?: number):从字符串中提取一部分,并返回一个新的字符串。startIndex为开始位置,endIndex为结束位置(不包含在返回的字符串中),如果不提供endIndex,则从startIndex一直到字符串的末尾。
const str: string = "hello world";
console.log(str.slice(6, 11));  // "world"
  1. substring(startIndex: number, endIndex?: number):与slice方法类似,不同的是substring不允许指定负数的索引,并且可以交换startIndex和endIndex的位置,截取的结果始终为原始字符串的子字符串。
const str: string = "hello world";
console.log(str.substring(0, 5));  // "hello"
console.log(str.substring(5, 0));  // "hello"
  1. toLowerCase():将字符串中的所有字母转换为小写字母,并返回新字符串。
const str: string = "Hello World";
console.log(str.toLowerCase());  // "hello world"
  1. toUpperCase():将字符串中的所有字母转换为大写字母,并返回新字符串。
const str: string = "Hello World";
console.log(str.toUpperCase());  // "HELLO WORLD"
  1. trim():去掉字符串开头和结尾的空格,并返回新字符串。
const str: string = "   hello world    ";
console.log(str.trim());  // "hello world"
  1. split(separator: string, limit?: number):将字符串分割成数组。separator为分隔符,limit为可选参数,表示返回的数组的最大长度。
const str: string = "hello,world";
console.log(str.split(","));  // ["hello", "world"]

总结

TypeScript String 是一种用于存储一系列字符的基本类型。我们可以使用单引号、双引号和反引号来定义字符串,也可以使用一些属性和方法来操作字符串。在这篇文章中,我们介绍了String类的一些常用属性和方法,以及它们的作用。掌握这些知识,能够更加方便地对字符串进行操作。