
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 编码,按参数顺序返回对应的字符。
标签: charAt, charCodeAt, fromCharCode, Unicode
上面是“charAt()、charCodeAt()和fromCharCode()的基本用法”的全面内容,想了解更多关于 js 内容,请继续关注web建站教程。
当前网址:https://m.ipkd.cn/webs_2070.html
声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!

wordpress添加文章字数统计和预计阅读时间代码
CopyTranslator官网:一款开源、免费且高效的翻译软件
GenSong AI:免费在线AI歌曲创作工具 零基础轻松生成专业级音乐
Udio APP最新版
ArticleRewriterTool:免费无门槛AI文本重写工具,高效优化各类写作内容
LivePortrait:快手科技与复旦大学联合开发的开源AI肖像动画技术框架
BrowserAct:一款AI网页爬虫工具,无需编码即时从任何网站提取数据