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.
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.
- 1 Please provide us with some code you've tried so far. – Krusader Commented Oct 18, 2017 at 12:53
4 Answers
Reset to default 7To 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)
Nothing fancy: you can replace the ⁵
character with the 5
character.
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⁷⁸⁹'));
It's also worth checking the String.prototype.normalize(form) function, it might do the trick.
console.log('n²'.normalize('NFKD'));
console.log('H₂O'.normalize('NFKD'));