[英]How to transform superscript number to real number in javascript
How can you transform a string containing a superscript to normal string? 如何将包含上标的字符串转换为普通字符串?
For example I have a string containing "n⁵"
. 例如,我有一个包含"n⁵"
的字符串。 I would like to transform it to "n5"
. 我想将其转换为"n5"
。 For the string "n⁵"
, i am not using any <sup></sup>
tags. 对于字符串"n⁵"
,我没有使用任何<sup></sup>
标记。 It is exactly like you see it. 就像您看到的一样。
To replace each character, you can assemble all the superscript characters in an ordered string (so that ⁰
is at index 0, ¹
is at index 1, etc.) and get their corresponding digit by indexOf
: 要替换每个字符,可以将所有上标字符组合成一个有序的字符串(以使at在索引0处, ¹
在索引1处,依此⁰
),并通过indexOf
获得其对应的数字:
function digitFromSuperscript(superChar) {
var result = "⁰¹²³⁴⁵⁶⁷⁸⁹".indexOf(superChar);
if(result > -1) { return result; }
else { return superChar; }
}
You can then run each character in your string through this function. 然后,您可以通过此函数运行字符串中的每个字符。 For example, you can do so by a replace
callback: 例如,您可以通过replace
回调来实现:
"n⁵".replace(/./g, digitFromSuperscript)
Or more optimally, limit the replace to only consider superscript characters: 或更佳地,将替换限制为仅考虑上标字符:
"n⁵".replace(/[⁰¹²³⁴⁵⁶⁷⁸⁹]/g, digitFromSuperscript)
Nothing fancy: you can replace the ⁵
character with the 5
character. 没什么好说的:您可以将⁵
字符替换为5
字符。
var result = "n⁵".replace("⁵", "5"); console.log(result);
You can use regex replacement with a replacement function: 您可以将正则表达式替换与替换功能一起使用:
function replaceSupers(str) { var superMap = { '⁰': '0', '¹': '1', '²': '2', '³': '3', '⁴': '4', '⁵': '5', '⁶': '6', '⁷': '7', '⁸': '8', '⁹': '9' } return str.replace(/[⁰¹²³⁴⁵⁶⁷⁸⁹]/g, function(match) { return superMap[match]; }); } console.log(replaceSupers('a¹²n⁴⁵lala⁷⁸⁹'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.