How can you transform a string containing a superscript to normal string?
For example I have a string containing "n⁵"
. I would like to transform it to "n5"
. For the string "n⁵"
, i am not using any <sup></sup>
tags. 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
:
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:
"n⁵".replace(/./g, digitFromSuperscript)
Or more optimally, limit the replace to only consider superscript characters:
"n⁵".replace(/[⁰¹²³⁴⁵⁶⁷⁸⁹]/g, digitFromSuperscript)