web建站教程
  1. 首页
  2. vuejs
  3. js
  4. 好玩
  5. seo教程
  6. 前端知识
  7. 百度echarts
  8. 更多
    php入门
    nodejs
    mockjs
    reactjs
    mysql
    wordpress
    织梦cms
    帝国cms
    git教程
    IT知识
    模板大全
    休息站

charAt()、charCodeAt()和fromCharCode()的基本用法

579 ℃
     

charAt()是按位置返回字符;charCodeAt()是按位置返回对应字符的Unicode编码;fromCharCode()则是根据字符的Unicode编码返回对应的字符。

1、charAt() 方法

var web  = "欢迎来到web建站";
console.log("字符串变量web的第1个字符是:'"+str.charAt(0)+"'"); // 欢
console.log("字符串变量web的第2个字符是:'"+str.charAt(1)+"'"); // 迎
console.log("字符串变量web的第5个字符是:'"+str.charAt(4)+"'"); // w

Ps:charAt() 返回 str 字符串中指定位置的单个字符。之前我们介绍了字符在字符串中的位置使用索引来表示,字符索引的取值从 0 开始依次递增。

2、charCodeAt() 方法

var w1  = "AB";
var w2  = "ab";
var w3  = "12";
var w4  = "中国";
console.log("'AB'字符串的第1个字符的Unicode编码为:"+w1.charCodeAt(0)); //65
console.log("'AB'字符串的第2个字符的Unicode编码为:"+w1.charCodeAt(1)); //66
console.log("'ab'字符串的第1个字符的Unicode编码为:"+w2.charCodeAt(0)); //97
console.log("'ab'字符串的第2个字符的Unicode编码为:"+w2.charCodeAt(1)); //98
console.log("'12'字符串的第1个字符的Unicode编码为:"+w3.charCodeAt(0)); //49
console.log("'12'字符串的第2个字符的Unicode编码为:"+w3.charCodeAt(1)); //50
console.log("'中国'字符串的第1个字符的Unicode编码为:"+w4.charCodeAt(0)); //20013
console.log("'中国'字符串的第2个字符的Unicode编码为:"+w4.charCodeAt(1)); //22269

Ps:charCodeAt() 返回 str 字符串指定位置处字符的 Unicode 编码,Unicode 编码取值范围为 0~1114111,其中前 128 个 Unicode 编码和 ASCII 字符编码一样。需要注意的是,如果指定的位置索引值小于 0 或大于字符串的长度,则 charCodeAt() 将返回 NaN。

3、fromCharCode() 方法

console.log("Unicode编码为21的字符是:"+String.fromCharCode(21)); //
console.log("Unicode编码为311的字符是:"+String.fromCharCode(311)); //ķ
console.log("Unicode编码为998的字符是:"+String.fromCharCode(998)); //Ϧ
console.log("Unicode编码为65的字符是:"+String.fromCharCode(65)); //A
console.log("Unicode编码为2022的字符是:"+String.fromCharCode(2022)); //ߦ
console.log("Unicode编码为520的字符是:"+String.fromCharCode(520)); //Ȉ
console.log("Unicode编码为13和14的字符是:"+String.fromCharCode(13,14)); //

Ps:fromCharCode() 是静态方法,需要通过 String 来调用,所以应该写作 String.fromCharCode(),其中的参数可以包含 1 到多个 Unicode 编码,按参数顺序返回对应的字符。

js如何将Unicode转义字符转换为实际字符

js如何字符串转成Unicode编码

标签: charAt, charCodeAt, fromCharCode, Unicode

上面是“charAt()、charCodeAt()和fromCharCode()的基本用法”的全面内容,想了解更多关于 js 内容,请继续关注web建站教程。

当前网址:https://ipkd.cn/webs_2070.html

声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!

当前位置: 网站首页 > js
本文共计1701个字,预计阅读时长12分钟
生活小工具,收录了80多款小工具
上一篇: 推荐一款免费开源的屏幕录制软件——OBS Studio
下一篇: 推荐一个高质量的图片素材网站——Unsplash
x 打工人ai神器