Skip to content

TypeScript String 类型

在 TypeScript 中,String 是一种基本数据类型,用于表示文本数据。字符串是由零个或多个字符组成的序列,可以使用单引号、双引号或反引号(模板字符串)来表示。本文将详细介绍 TypeScript 中的 String 类型。

1. 基本用法

声明 String 类型变量

typescript
let name: string = "John";
let message: string = 'Hello, world!';
let emptyString: string = "";

字符串字面量

TypeScript 支持三种字符串字面量形式:

  • 单引号'Hello'
  • 双引号"Hello"
  • 反引号(模板字符串):`Hello`
typescript
let singleQuote: string = 'Hello';
let doubleQuote: string = "Hello";
let templateLiteral: string = `Hello`;

2. 字符串模板

模板字符串使用反引号(`)包围,可以在其中插入表达式,使用 ${表达式} 的形式。

基本用法

typescript
let name: string = "John";
let age: number = 30;

// 模板字符串
let message: string = `Hello, ${name}! You are ${age} years old.`;
console.log(message); // 输出:Hello, John! You are 30 years old.

// 多行模板字符串
let multiLine: string = `
  This is a
  multi-line
  string
`;
console.log(multiLine);
// 输出:
// 
//   This is a
//   multi-line
//   string
//

// 表达式计算
let a: number = 10;
let b: number = 20;
let result: string = `The sum of ${a} and ${b} is ${a + b}.`;
console.log(result); // 输出:The sum of 10 and 20 is 30.

3. 内置方法

字符串长度

typescript
let str: string = "Hello, world!";
console.log(str.length); // 输出:13

访问字符

typescript
let str: string = "Hello";
console.log(str[0]); // 输出:H
console.log(str[1]); // 输出:e
console.log(str[str.length - 1]); // 输出:o

字符串方法

charAt()

返回指定位置的字符。

typescript
let str: string = "Hello";
console.log(str.charAt(0)); // 输出:H
console.log(str.charAt(1)); // 输出:e

charCodeAt()

返回指定位置字符的 Unicode 编码。

typescript
let str: string = "Hello";
console.log(str.charCodeAt(0)); // 输出:72('H' 的 Unicode 编码)
console.log(str.charCodeAt(1)); // 输出:101('e' 的 Unicode 编码)

concat()

连接两个或多个字符串。

typescript
let str1: string = "Hello";
let str2: string = "World";
console.log(str1.concat(" ", str2)); // 输出:Hello World

indexOf()

返回指定子字符串第一次出现的位置,如果没有找到则返回 -1。

typescript
let str: string = "Hello, world!";
console.log(str.indexOf("world")); // 输出:7
console.log(str.indexOf("test")); // 输出:-1

lastIndexOf()

返回指定子字符串最后一次出现的位置,如果没有找到则返回 -1。

typescript
let str: string = "Hello, hello, hello!";
console.log(str.lastIndexOf("hello")); // 输出:14

includes()

检查字符串是否包含指定的子字符串,返回布尔值。

typescript
let str: string = "Hello, world!";
console.log(str.includes("world")); // 输出:true
console.log(str.includes("test")); // 输出:false

startsWith()

检查字符串是否以指定的子字符串开头,返回布尔值。

typescript
let str: string = "Hello, world!";
console.log(str.startsWith("Hello")); // 输出:true
console.log(str.startsWith("World")); // 输出:false

endsWith()

检查字符串是否以指定的子字符串结尾,返回布尔值。

typescript
let str: string = "Hello, world!";
console.log(str.endsWith("world!")); // 输出:true
console.log(str.endsWith("Hello")); // 输出:false

slice()

提取字符串的一部分,返回新字符串。

typescript
let str: string = "Hello, world!";
console.log(str.slice(7)); // 输出:world!
console.log(str.slice(0, 5)); // 输出:Hello
console.log(str.slice(-6)); // 输出:world!

substring()

提取字符串的一部分,返回新字符串(与 slice 类似,但参数处理不同)。

typescript
let str: string = "Hello, world!";
console.log(str.substring(7)); // 输出:world!
console.log(str.substring(0, 5)); // 输出:Hello

substr()

提取字符串的一部分,返回新字符串(已废弃,建议使用 slice)。

typescript
let str: string = "Hello, world!";
console.log(str.substr(7)); // 输出:world!
console.log(str.substr(0, 5)); // 输出:Hello

replace()

替换字符串中的指定子字符串,返回新字符串。

typescript
let str: string = "Hello, world!";
console.log(str.replace("world", "TypeScript")); // 输出:Hello, TypeScript!

// 使用正则表达式
let str2: string = "Hello, hello, hello!";
console.log(str2.replace(/hello/g, "hi")); // 输出:Hello, hi, hi!

replaceAll()

替换字符串中所有指定的子字符串,返回新字符串。

typescript
let str: string = "Hello, hello, hello!";
console.log(str.replaceAll("hello", "hi")); // 输出:Hello, hi, hi!

toUpperCase()

将字符串转换为大写。

typescript
let str: string = "Hello, world!";
console.log(str.toUpperCase()); // 输出:HELLO, WORLD!

toLowerCase()

将字符串转换为小写。

typescript
let str: string = "Hello, world!";
console.log(str.toLowerCase()); // 输出:hello, world!

trim()

去除字符串两端的空白字符。

typescript
let str: string = "   Hello, world!   ";
console.log(str.trim()); // 输出:Hello, world!

trimStart()

去除字符串开头的空白字符。

typescript
let str: string = "   Hello, world!   ";
console.log(str.trimStart()); // 输出:Hello, world!

trimEnd()

去除字符串结尾的空白字符。

typescript
let str: string = "   Hello, world!   ";
console.log(str.trimEnd()); // 输出:   Hello, world!

split()

将字符串分割为数组。

typescript
let str: string = "Hello, world!";
console.log(str.split(", ")); // 输出:["Hello", "world!"]

let str2: string = "a,b,c,d";
console.log(str2.split(",")); // 输出:["a", "b", "c", "d"]

let str3: string = "Hello";
console.log(str3.split("")); // 输出:["H", "e", "l", "l", "o"]

repeat()

将字符串重复指定次数,返回新字符串。

typescript
let str: string = "Hello";
console.log(str.repeat(3)); // 输出:HelloHelloHello

padStart()

在字符串开头填充指定字符,直到达到指定长度。

typescript
let str: string = "123";
console.log(str.padStart(5, "0")); // 输出:00123
console.log(str.padStart(10, "*")); // 输出:*******123

padEnd()

在字符串结尾填充指定字符,直到达到指定长度。

typescript
let str: string = "123";
console.log(str.padEnd(5, "0")); // 输出:12300
console.log(str.padEnd(10, "*")); // 输出:123*******

valueOf()

返回字符串的原始值。

typescript
let str: string = "Hello";
console.log(str.valueOf()); // 输出:Hello

toString()

返回字符串的字符串表示。

typescript
let str: string = "Hello";
console.log(str.toString()); // 输出:Hello

4. 类型转换

其他类型转字符串

typescript
// 使用 String() 函数
let num: number = 123;
let str1: string = String(num);
console.log(str1); // 输出:"123"

let bool: boolean = true;
let str2: string = String(bool);
console.log(str2); // 输出:"true"

let obj: object = { name: "John" };
let str3: string = String(obj);
console.log(str3); // 输出:"[object Object]"

// 使用 toString() 方法
let num2: number = 123;
let str4: string = num2.toString();
console.log(str4); // 输出:"123"

// 使用模板字符串
let num3: number = 123;
let str5: string = `${num3}`;
console.log(str5); // 输出:"123"

字符串转数字

typescript
// 使用 Number() 函数
let str1: string = "123";
let num1: number = Number(str1);
console.log(num1); // 输出:123

// 使用 parseInt() 函数
let str2: string = "123.45";
let num2: number = parseInt(str2);
console.log(num2); // 输出:123

// 使用 parseFloat() 函数
let str3: string = "123.45";
let num3: number = parseFloat(str3);
console.log(num3); // 输出:123.45

// 使用一元加号运算符
let str4: string = "123";
let num4: number = +str4;
console.log(num4); // 输出:123

字符串转布尔值

typescript
let str1: string = "true";
let bool1: boolean = Boolean(str1);
console.log(bool1); // 输出:true

let str2: string = "false";
let bool2: boolean = Boolean(str2);
console.log(bool2); // 输出:true(非空字符串都为 true)

let str3: string = "";
let bool3: boolean = Boolean(str3);
console.log(bool3); // 输出:false

5. 类型守卫

在 TypeScript 中,可以使用类型守卫来检查一个值是否是字符串类型。

typeof 类型守卫

typescript
function processValue(value: string | number) {
  if (typeof value === "string") {
    // 在这个分支中,TypeScript 知道 value 是 string 类型
    console.log(value.toUpperCase());
  } else {
    // 在这个分支中,TypeScript 知道 value 是 number 类型
    console.log(value.toFixed(2));
  }
}

processValue("hello"); // 输出:HELLO
processValue(123.45); // 输出:123.45

自定义类型守卫

typescript
function isString(value: any): value is string {
  return typeof value === "string";
}

function processValue(value: any) {
  if (isString(value)) {
    // 在这个分支中,TypeScript 知道 value 是 string 类型
    console.log(value.toUpperCase());
  } else {
    console.log("Not a string");
  }
}

processValue("hello"); // 输出:HELLO
processValue(123); // 输出:Not a string
processValue(true); // 输出:Not a string

6. 字符串操作的最佳实践

1. 使用模板字符串

对于包含变量或表达式的字符串,使用模板字符串可以使代码更清晰。

typescript
// 推荐
let name: string = "John";
let age: number = 30;
let message: string = `Hello, ${name}! You are ${age} years old.`;

// 不推荐
let name: string = "John";
let age: number = 30;
let message: string = "Hello, " + name + "! You are " + age + " years old.";

2. 使用字符串方法

对于字符串操作,优先使用内置的字符串方法,而不是自己实现。

typescript
// 推荐
let str: string = "   Hello, world!   ";
let trimmedStr: string = str.trim();

// 不推荐
let str: string = "   Hello, world!   ";
let trimmedStr: string = str.replace(/^\s+|\s+$/g, "");

3. 注意字符串的不可变性

字符串是不可变的,每次修改字符串都会创建一个新的字符串。

typescript
// 字符串是不可变的
let str: string = "Hello";
str[0] = "h"; // 不会修改原字符串
console.log(str); // 输出:Hello

// 正确的做法是创建新字符串
let str: string = "Hello";
let newStr: string = "h" + str.slice(1);
console.log(newStr); // 输出:hello

4. 使用 includes() 替代 indexOf()

对于检查字符串是否包含子字符串,使用 includes() 方法更清晰。

typescript
// 推荐
let str: string = "Hello, world!";
if (str.includes("world")) {
  // 包含
}

// 不推荐
let str: string = "Hello, world!";
if (str.indexOf("world") !== -1) {
  // 包含
}

5. 合理使用正则表达式

对于复杂的字符串操作,使用正则表达式可以提高效率。

typescript
// 提取数字
let str: string = "The price is $123.45";
let price: number = parseFloat(str.match(/\d+\.\d+/)![0]);
console.log(price); // 输出:123.45

// 替换多个空格为单个空格
let str: string = "Hello   world!";
let newStr: string = str.replace(/\s+/g, " ");
console.log(newStr); // 输出:Hello world!

7. 常见错误

1. 字符串的不可变性

尝试直接修改字符串的字符会失败,因为字符串是不可变的。

typescript
// 错误
let str: string = "Hello";
str[0] = "h"; // 不会修改原字符串
console.log(str); // 输出:Hello

// 正确
let str: string = "Hello";
let newStr: string = "h" + str.slice(1);
console.log(newStr); // 输出:hello

2. 类型转换错误

在进行字符串转换时,可能会得到意外的结果。

typescript
// 错误:字符串转数字
let str: string = "abc";
let num: number = Number(str); // NaN

// 错误:对象转字符串
let obj: object = { name: "John" };
let str: string = String(obj); // "[object Object]"

3. 正则表达式使用错误

在使用正则表达式时,需要注意语法和标志。

typescript
// 错误:忘记添加全局标志
let str: string = "Hello, hello, hello!";
let newStr: string = str.replace("hello", "hi"); // 只替换第一个匹配项
console.log(newStr); // 输出:Hello, hi, hello!

// 正确:添加全局标志
let str: string = "Hello, hello, hello!";
let newStr: string = str.replace(/hello/g, "hi"); // 替换所有匹配项
console.log(newStr); // 输出:Hello, hi, hi!

4. 字符串方法的返回值

许多字符串方法返回新字符串,而不是修改原字符串。

typescript
// 错误:忘记使用返回值
let str: string = "Hello";
str.toUpperCase(); // 原字符串不变
console.log(str); // 输出:Hello

// 正确:使用返回值
let str: string = "Hello";
let upperStr: string = str.toUpperCase();
console.log(upperStr); // 输出:HELLO

5. 模板字符串中的表达式

在模板字符串中,表达式需要使用 ${} 包围。

typescript
// 错误:忘记使用 ${}
let name: string = "John";
let message: string = `Hello, name!`; // 输出:Hello, name!

// 正确:使用 ${}
let name: string = "John";
let message: string = `Hello, ${name}!`; // 输出:Hello, John!

总结

TypeScript 中的 String 类型是一种基本数据类型,用于表示文本数据。它包括:

  • 基本用法:使用单引号、双引号或反引号声明字符串
  • 字符串模板:使用反引号和 ${} 插入表达式
  • 内置方法:提供了丰富的字符串操作方法
  • 类型转换:与其他类型之间的转换
  • 类型守卫:检查一个值是否是字符串类型
  • 最佳实践:使用模板字符串、字符串方法、注意字符串的不可变性等
  • 常见错误:字符串的不可变性、类型转换错误、正则表达式使用错误等

通过合理使用 String 类型和相关方法,你可以在 TypeScript 中处理各种文本操作,编写更清晰、更高效的代码。