You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Node.js(Discord.js V14)中将整数转为上标数字?

解决方案

有几种简洁的方式可以实现数字到上标字符的转换,以下是具体实现:

方法一:字符映射替换

创建数字与上标字符的映射表,通过字符串替换完成转换,支持多位数处理:

const number = "123";
// 数字到上标字符的映射表
const superscriptMap = {
  '0': '⁰',
  '1': '¹',
  '2': '²',
  '3': '³',
  '4': '⁴',
  '5': '⁵',
  '6': '⁶',
  '7': '⁷',
  '8': '⁸',
  '9': '⁹'
};
// 转换函数
const toSuperscript = num => num.toString().split('').map(char => superscriptMap[char]).join('');

const superscriptNum = toSuperscript(number); // 结果为 "¹²³"
// 应用到昵称设置
const user = interaction.options.getMember('user');
user.setNickname(`nickname${superscriptNum}`);

方法二:Unicode编码计算

利用上标数字的Unicode编码规律直接生成字符,同样支持多位数:

const number = 3;
// 转换函数
const toSuperscript = num => {
  return num.toString().split('').map(digit => {
    const code = parseInt(digit);
    if (code === 0) return '⁰';
    if (code === 1) return '¹';
    if (code === 2) return '²';
    // 3-9的上标Unicode编码从0x2073开始,对应code+0x2070
    return String.fromCharCode(0x2070 + code);
  }).join('');
};

const superscriptNum = toSuperscript(number); // 结果为 "³"
// 应用到昵称设置
const user = interaction.options.getMember('user');
user.setNickname(`nickname${superscriptNum}`);

两种方法都可直接集成到你的代码中,适配整数或数字字符串的转换需求,支持多位数场景。

内容的提问来源于stack exchange,提问作者LonelyChimo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 04:10:02