概述
-
在 JavaScript 中,String 提供了多个用于访问字符的方法
-
包括 at、charAt、charCodeAt、codePointAt 方法
一、at 方法
1、基本介绍
- at 方法用于返回字符串指定位置的字符,且支持负数索引
at(index)
参数 | 说明 |
---|---|
index | 指定要返回的字符的索引 可以是正数,即从左往右,也可以是负数,即从右往左,例如,-1 表示最后一个字符 负数 index + 字符串长度 = 正数 index |
- 返回值:如果 index 有效,返回对应的字符,如果 index 超出范围,返回 undefined
2、演示
const str = "Hello";
let result1 = str.at(0);
let result2 = str.at(-1);
let result3 = str.at(10);
console.log(result1);
console.log(result2);
console.log(result3);
# 输出结果
H
o
undefined
二、charAt 方法
1、基本介绍
- charAt 方法用于返回字符串指定位置的字符,但不支持负数索引
charAt(index)
参数 | 说明 |
---|---|
index | 指定要返回的字符的索引 |
- 返回值:如果 index 有效,返回对应的字符,如果 index 超出范围,返回空字符串
""
2、演示
const str = "Hello";
let result1 = str.charAt(0);
let result2 = str.charAt(-1);
let result3 = str.charAt(10);
console.log(result1);
console.log(result2);
console.log(result2 === "");
console.log(result3);
console.log(result3 === "");
# 输出结果
H
true
true
三、charCodeAt 方法
1、基本介绍
- charCodeAt 方法用于返回字符串指定位置的字符的
UTF-16
编码,即0 ~ 65535
charCodeAt(index)
参数 | 说明 |
---|---|
index | 指定要返回的字符的索引 |
-
返回值:如果 index 有效,返回对应的字符的
UTF-16
编码,如果 index 超出范围,返回 NaN -
注:适用于基本多文种平面字符,例如,英文、常用汉字,但无法正确处理辅助平面字符,例如,emoji
2、演示
- 基本使用
const str = "Hello";
let result1 = str.charCodeAt(0);
let result2 = str.charCodeAt(-1);
let result3 = str.charCodeAt(10);
console.log(result1);
console.log(result2);
console.log(result3);
# 输出结果
72
NaN
NaN
- 处理基本多文种平面字符与辅助平面字符
const str = "A";
let result1 = str.charCodeAt(0);
console.log(result1);
const emoji = "😊";
let result2 = emoji.charCodeAt(0);
console.log(result2);
# 输出结果
65
55357
四、codePointAt 方法
1、基本介绍
- codePointAt 方法用于返回字符串指定位置的字符的 Unicode 码点,即完整的编码
codePointAt(index)
参数 | 说明 |
---|---|
index | 指定要返回的字符的索引 |
-
返回值:如果 index 有效,返回对应的字符的 Unicode 码点,如果 index 超出范围,返回 undefined
-
注:适用于所有字符,包括基本多文种平面字符和辅助平面字符
2、演示
- 基本使用
const str = "Hello";
let result1 = str.codePointAt(0);
let result2 = str.codePointAt(-1);
let result3 = str.codePointAt(10);
console.log(result1);
console.log(result2);
console.log(result3);
# 输出结果
72
undefined
undefined
- 处理基本多文种平面字符与辅助平面字符
const str = "A";
let result1 = str.codePointAt(0);
console.log(result1);
const emoji = "😊";
let result2 = emoji.codePointAt(0);
console.log(result2);
# 输出结果
65
128522