返回

用字符串的内置方法处理字符串

Android

字符串是 JavaScript 中的基本类型之一,用于表示文本数据。字符串可以使用字面量或通过 new 来创建。

使用字面量创建字符串

字符串字面量是使用引号(单引号或双引号)括起来的一系列字符。例如:

let str = "Hello world!";

使用 new 创建字符串

也可以使用 new 关键字来创建字符串对象。语法如下:

let str = new String("Hello world!");

使用 new 创建的字符串对象与使用字面量创建的字符串字面量在功能上是相同的,但它们在底层实现上有所不同。字符串字面量是原始值,而字符串对象是引用类型。

字符串的长度

字符串的长度可以通过 length 属性来获取。例如:

let str = "Hello world!";
console.log(str.length); // 13

字符串的内置方法

字符串对象提供了许多内置方法,用于处理字符串。这些方法包括:

  • indexOf():查找指定子字符串在字符串中第一次出现的位置。
  • lastIndexOf():查找指定子字符串在字符串中最后一次出现的位置。
  • slice():从字符串中提取子字符串。
  • substring():从字符串中提取子字符串。
  • toUpperCase():将字符串转换为大写。
  • toLowerCase():将字符串转换为小写。
  • trim():从字符串中删除前导和尾随空格。
  • replace():用另一个字符串替换字符串中的子字符串。

示例代码

以下是一些示例代码,演示如何使用字符串的内置方法:

let str = "Hello world!";

// 查找子字符串 "world" 在字符串中第一次出现的位置
let index = str.indexOf("world");
console.log(index); // 6

// 查找子字符串 "world" 在字符串中最后一次出现的位置
index = str.lastIndexOf("world");
console.log(index); // 6

// 从字符串中提取子字符串 "Hello"
let substring = str.slice(0, 5);
console.log(substring); // "Hello"

// 从字符串中提取子字符串 "world"
substring = str.substring(6);
console.log(substring); // "world!"

// 将字符串转换为大写
let upperCase = str.toUpperCase();
console.log(upperCase); // "HELLO WORLD!"

// 将字符串转换为小写
let lowerCase = str.toLowerCase();
console.log(lowerCase); // "hello world!"

// 从字符串中删除前导和尾随空格
let trimmed = str.trim();
console.log(trimmed); // "Hello world!"

// 用字符串 "Hi" 替换字符串中的子字符串 "Hello"
let replaced = str.replace("Hello", "Hi");
console.log(replaced); // "Hi world!"