Skip to content

ES6 - String 对象

在 JavaScript 中,字符串(String)是用于表示文本的字符序列。字符串基本类型(string primitives)是不可变的(immutable),意味着一旦创建,其内容就不能更改。String 对象是字符串基本数据类型的包装器(wrapper),提供了许多处理文本的有用方法。

JavaScript 会在字符串基本类型和 String 对象之间自动转换,因此您可以直接在字符串字面量或保存字符串基本类型的变量上调用 String 对象的方法。

// String literal (preferred for primitives)
// 字符串字面量(基本类型的首选)
const greeting = "Hello, World!";
const name = 'Alice';
// Using the String constructor (less common for creating primitives)
// 使用 String 构造函数(创建基本类型较少用)
// This creates a String object, not a primitive
// 这会创建一个 String 对象,而不是基本类型
const strObject = new String("I am an object");
console.log(typeof greeting); // "string"
console.log(typeof strObject); // "object"

String 对象(以及通过自动包装的字符串基本类型)具有以下属性:

序号属性描述
1constructor返回创建该实例原型的 String 函数的引用。通常在日常编码中不使用。
2length返回字符串中的字符数 (UTF-16 code units)。
const message = "JavaScript";
console.log(message.length); // 输出: 10

以下是字符串基本类型和 String 对象上常用的方法列表。请注意,字符串方法不会修改原始字符串;它们返回一个新字符串。

序号方法描述
1charAt(index)返回指定 index 位置的字符。
2charCodeAt(index)返回指定 index 位置字符的 UTF-16 code unit 值(一个数字)。
3concat(str1, str2, ..., strN)将一个或多个字符串的文本合并为一个新字符串并返回。(通常更倾向于使用 + 运算符进行连接)。
4includes(searchString, position?)ES6 方法:判断一个字符串是否包含 searchString,返回 true 或 false。可选参数 position 指定搜索的起始位置。
5endsWith(searchString, length?)ES6 方法:判断一个字符串是否以 searchString 的字符结尾,返回 true 或 false。可选参数 length 指定搜索的字符串长度。
6indexOf(searchValue, fromIndex?)返回在调用 String 对象中 searchValue 第一次出现的索引,如果未找到则返回 -1。可选参数 fromIndex 指定开始搜索的位置。
7lastIndexOf(searchValue, fromIndex?)返回在调用 String 对象中 searchValue 最后一次出现的索引,从 fromIndex 向后搜索,如果未找到则返回 -1。
8localeCompare(compareString, locales?, options?)返回一个数字,表示参考字符串在排序顺序中是位于给定字符串之前、之后还是相同,对语言环境敏感。
9match(regexp)检索字符串与正则表达式的匹配结果。
10matchAll(regexp)ES2020 方法:返回一个迭代器,包含字符串与正则表达式的所有匹配结果,包括捕获组。
11padStart(targetLength, padString?)ES2017 方法:从字符串开头使用给定的字符串填充(如有必要会重复),直到达到指定长度。
12padEnd(targetLength, padString?)ES2017 方法:从字符串末尾使用给定的字符串填充(如有必要会重复),直到达到指定长度。
13repeat(count)ES6 方法:构造并返回一个新字符串,其中包含调用该方法的字符串指定数量的副本,并连接在一起。count 必须是一个非负整数。
14replace(searchValue, replacer)返回一个新字符串,其中部分或全部 pattern 的匹配项被 replacement 替换。searchValue 可以是字符串或 RegExp。replacer 可以是字符串或函数。
15replaceAll(searchValue, replacer)ES2021 方法:返回一个新字符串,其中所有 pattern 的匹配项被 replacement 替换。searchValue 可以是字符串或 RegExp(如果设置了全局标志)。
16search(regexp)执行正则表达式与此 String 对象之间的匹配搜索。返回第一次匹配的索引,如果未找到则返回 -1。
17slice(beginIndex, endIndex?)提取字符串的一部分作为新字符串返回,不修改原字符串。endIndex 是非包含性的。
18split(separator?, limit?)使用指定的 separator 字符串作为分隔符,将一个 String 对象分割成字符串数组。
19startsWith(searchString, position?)ES6 方法:判断一个字符串是否以 searchString 的字符开头,返回 true 或 false。可选参数 position 指定搜索的起始位置。
20substring(indexStart, indexEnd?)返回字符串在 indexStart 和 indexEnd 索引之间的部分,或者到字符串的末尾。如果 indexStart 大于 indexEnd,则交换参数。
21toLowerCase()将调用字符串的值转换为小写并返回。
22toLocaleLowerCase(locales?)将字符串中的字符转换为小写,同时考虑当前或指定的语言环境。
23toUpperCase()将调用字符串的值转换为大写并返回。
24toLocaleUpperCase(locales?)将字符串中的字符转换为大写,同时考虑当前或指定的语言环境。
25trim()移除字符串两端的空白字符。
26trimStart() / trimLeft()ES2019 方法:移除字符串开头的空白字符。
27trimEnd() / trimRight()ES2019 方法:移除字符串末尾的空白字符。
28valueOf()返回 String 对象的基本类型值。

substr(start, length) 方法在 ECMAScript 中被认为是历史遗留特性(legacy feature),不推荐使用。它可能在未来版本中被移除。请改用 substring(start, end) 或 slice(start, end)。

const text = " Hello ES6 World! ";
console.log(`Original: '${text}'`);
console.log(`Length: ${text.length}`);
console.log(`charAt(3): ${text.charAt(3)}`); // 'e' (概念上去除空白后)
console.log(`includes('ES6'): ${text.includes('ES6')}`); // true
console.log(`indexOf('World'): ${text.indexOf('World')}`); // 11 (概念上去除空白后)
console.log(`slice(8, 11): '${text.trim().slice(6, 9)}'`); // 'ES6'
console.log(`toUpperCase(): '${text.toUpperCase()}'`); // 输出: ' HELLO ES6 WORLD! '
console.log(`trim(): '${text.trim()}'`); // 输出: 'Hello ES6 World!'
console.log(`split(' '):`, text.trim().split(' ')); // 输出: ["Hello", "ES6", "World!"]

有关所有字符串方法的全面详细信息,请参考 MDN Web 文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String