jquery - How to transform superscript number to real number in javascript - Stack Overflow

How can you transform a string containing a superscript to normal string?For example I have a string co

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.

Share Improve this question edited Oct 18, 2017 at 12:55 Rory McCrossan 338k41 gold badges320 silver badges351 bronze badges asked Oct 18, 2017 at 12:52 M.MalacnikM.Malacnik 233 bronze badges 1
  • 1 Please provide us with some code you've tried so far. – Krusader Commented Oct 18, 2017 at 12:53
Add a ment  | 

4 Answers 4

Reset to default 7

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)

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'));

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744280408a4566540.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信