String.prototype.charAt()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

StringcharAt() 方法返回一个由给定索引处的单个 UTF-16 码元构成的新字符串。

charAt() 方法总是将字符串作为 UTF-16 码元序列进行索引,因此它可能会返回孤项代理。要获取给定索引处的完整 Unicode 码位,请使用 String.prototype.codePointAt()String.fromCodePoint()

尝试一下

const sentence = "The quick brown fox jumps over the lazy dog.";

const index = 4;

console.log(`The character at index ${index} is ${sentence.charAt(index)}`);
// Expected output: "The character at index 4 is q"

语法

js
charAt(index)

参数

index

要返回的字符的索引,从零开始。会被转换为整数——undefined 会被转换为 0。

返回值

返回一个字符串,该字符串表示指定 index 处的字符(恰好是一个 UTF-16 码元)。如果 index 超出了 0str.length - 1 的范围,charAt() 将返回一个空字符串。

描述

字符串中的字符从左到右进行索引。第一个字符的索引为 0,字符串中最后一个字符的索引为 str.length - 1

Unicode 码位的范围从 01114111 (0x10FFFF)。charAt() 方法总是返回一个其值小于 65536 的字符,因为更高的码位是由一对 16 位代理伪字符表示的。因此,为了获取值大于 65535 的完整字符,需要检索不仅是 charAt(i),还要检索 charAt(i + 1)(就像操作一个由两个字符组成的字符串一样),或者使用 codePointAt(i)String.fromCodePoint() 代替。有关 Unicode 的信息,请参阅 UTF-16 字符、Unicode 码位和字素簇

charAt() 和使用方括号表示法访问指定索引处的字符非常相似。它们的主要区别在于:

  • charAt() 尝试将 index 转换为整数,而方括号表示法不会,直接使用 index 作为属性名。
  • 如果 index 超出范围,charAt() 返回一个空字符串,而方括号表示法返回 undefined

示例

使用 charAt()

下例输出字符串 "Brave new world" 不同位置处的字符:

js
const anyString = "Brave new world";
console.log(`在索引 0 处的字符为 '${anyString.charAt()}'`);
// 没有提供索引,使用 0 作为默认值

console.log(`在索引 0 处的字符为 '${anyString.charAt(0)}'`);
console.log(`在索引 1 处的字符为 '${anyString.charAt(1)}'`);
console.log(`在索引 2 处的字符为 '${anyString.charAt(2)}'`);
console.log(`在索引 3 处的字符为 '${anyString.charAt(3)}'`);
console.log(`在索引 4 处的字符为 '${anyString.charAt(4)}'`);
console.log(`在索引 999 处的字符为 '${anyString.charAt(999)}'`);

上面代码的输出为:

在索引 0 处的字符为 'B'

在索引 0 处的字符为 'B'
在索引 1 处的字符为 'r'
在索引 2 处的字符为 'a'
在索引 3 处的字符为 'v'
在索引 4 处的字符为 'e'
在索引 999 处的字符为 ''

charAt() 可能会返回孤项代理,这些代理项不是有效的 Unicode 字符。

js
const str = "𠮷𠮾";
console.log(str.charAt(0)); // "\ud842",这不是有效的 Unicode 字符
console.log(str.charAt(1)); // "\udfb7",这不是有效的 Unicode 字符

要获取给定索引处的完整 Unicode 码位,请使用按 Unicode 码位拆分的索引方法,例如 String.prototype.codePointAt() 和将字符串展开为 Unicode 码位数组

js
const str = "𠮷𠮾";
console.log(String.fromCodePoint(str.codePointAt(0))); // "𠮷"
console.log([...str][0]); // "𠮷"

备注: 避免使用 charAt() 重新实现上述解决方案。检测孤项代理及其配对很复杂,而内置 API 可能更高效,因为它们直接使用字符串的内部表示形式。如有必要,请安装上述 API 的 polyfill。

规范

Specification
ECMAScript® 2025 Language Specification
# sec-string.prototype.charat

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
charAt

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见