JavaScript 字符串 - 访问字符(at 方法、charAt 方法、charCodeAt 方法、codePointAt 方法)

概述

  1. 在 JavaScript 中,String 提供了多个用于访问字符的方法

  2. 包括 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、演示
  1. 基本使用
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
  1. 处理基本多文种平面字符与辅助平面字符
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、演示
  1. 基本使用
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
  1. 处理基本多文种平面字符与辅助平面字符
const str = "A";

let result1 = str.codePointAt(0);

console.log(result1);

const emoji = "😊";

let result2 = emoji.codePointAt(0);

console.log(result2);
# 输出结果

65
128522
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值