如何使用通用正则表达式将文本中的上标数字替换为普通数字?
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

