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

如何使用通用正则表达式将文本中的上标数字替换为普通数字?

Solution for Replacing All Superscript Digits with Regular Digits

Got it! Your current approach works for ² and ³, but to handle all superscript digits (0-9) in one clean step, you can use a regex that matches every superscript digit character paired with a replacement map. Here's how to do it:

Step 1: Create a mapping of superscript digits to regular digits

First, define an object that maps each superscript character to its corresponding regular digit. This covers all common superscript digits you'll encounter:

const superscriptToRegular = {
  '⁰': '0',
  '¹': '1',
  '²': '2',
  '³': '3',
  '⁴': '4',
  '⁵': '5',
  '⁶': '6',
  '⁷': '7',
  '⁸': '8',
  '⁹': '9'
};

Step 2: Use a single regex replace with a callback function

Instead of chaining multiple replace() calls, use a regex that matches any of the superscript digits (using a character set [⁰¹²³⁴⁵⁶⁷⁸⁹]) and the g flag to replace all occurrences. The callback function looks up each matched character in our map and returns the regular digit:

const originalText = "V is 100 m³, square is 12 m², 7⁴ equals 2401, and 10⁰ is 1";
const convertedText = originalText.replace(/[⁰¹²³⁴⁵⁶⁷⁸⁹]/g, match => superscriptToRegular[match]);

console.log(convertedText);
// Output: "V is 100 m3, square is 12 m2, 74 equals 2401, and 100 is 1"

Quick typo note

Your original code has a small typo (repalce instead of replace)—just something to watch out for!

Why this works better

  • Covers all digits: No need to add a new replace() call for every superscript digit you find.
  • Easy to extend: If you ever need to handle other superscript characters (like fractions or symbols), you can just add them to the mapping object.
  • Clean and maintainable: One single replacement step makes your code easier to read and update.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:33:25