[Question]
  [
CGCC hasn't always had MathJax. Back in the dark ages, it would have been necessary to write \$x^2\$ as `x²` (the horror!). In this challenge, you will be given some math which may include superscripts, and you should convert it to MathJax.
**Input:**
Input will consist of one or more letters `a` to `z`, some with superscripts. Answers may choose to handle only upper or lower case, or both.
Examples of inputs would be `x`, `x²`, `xy²`, `x²y²`, or `x²yz`. There will never be duplicates of a letter (so `xx` or `x²zx` won't be given), but you cannot assume the superscripts or letters are in any particular order. The first character in the input will never be a superscript.
Superscripts consist of the characters `¹`, `²`, `³`, `⁴`, `⁵`, `⁶`, `⁷`, `⁸`, `⁹`, and `⁰`. These can be joined into multi-digit superscripts, like x²¹ (\$x^{21}\$). You can assume `⁰` or `¹` are never given as superscripts, and there will not be leading `⁰`s.
**Output:**
Output should consist of a MathJax representation of the input. This must start and finish with `\$`.
Characters without superscripts can be written as themselves; `xyz` would simply become `\$xyz\$`. Characters with superscripts should be followed by `^`, then the superscript written with normal digits and wrapped in `{}`. For example, `x²¹z⁴⁸⁸` would become `\$x^{21}z^{488}\$`. Optionally, single digit superscripts can be written without the `{}`. For example, `x²` could be either `\$x^{2}\$` or `\$x^2\$`.
**Test cases:**
```
x           \$x\$
xyz         \$xyz\$
x²          \$x^{2}\$ OR \$x^2\$
x²¹         \$x^{21}\$
x²yz²       \$x^{2}yz^{2}\$ OR \$x^2yz^2\$
xy¹¹z       \$xy^{11}z\$
x⁴          \$x^{4}\$ OR \$x^4\$
x⁶⁰         \$x^{60}\$
```
**Other:**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer (in bytes) per language wins!
  
[Answer]
# JavaScript, 55 bytes
```
e=>`\\$${e.normalize`NFKD`.replace(/\d+/g,`^{$&}`)}\\$`
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/V1i4hJkZFpTpVLy@/KDcxJ7MqNcHPzdslQa8otSAnMTlVQz8mRVs/XSchrlpFrTZBsxaoPOF/cn5ecX5Oql5OfrpGmkZCRYKmJhe6WGUVNtFDm7CLHtqJXbyyCruOykM7D@3EasOjxi3Yhbc9atwAlPkPAA)
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~43 41~~ 40 bytes
```
`JD;"¦$"ṁ?Iȯ:'^`J"{}"ṁos€"¹²³⁴⁵⁶⁷⁸⁹"Λ√ġ√
```
[Try it online!](https://tio.run/##yygtzv7/P8HLxVrp0DIVpYc7G@09T6y3Uo9L8FKqrgXx84sfNa1ROrTz0KZDmx81bnnUuPVR47ZHjdsfNe541LhT6dzsRx2zjiwEEv///684tKmy6tAmAA "Husk – Try It Online")
The superscripts are 1 byte each since they're in Husk's codepage.
I wanted to replace `+₁+₁` with `S+`+"¦$"` but it didn't work for some reason.. :(
-2 bytes borrowing the indexing idea from hyper-neutrino.
-1 byte from Leo.
## Explanation
```
`JD;"¦$"ṁ?Iȯ`:'}+"^{"ṁos€"¹..⁹"Λ√ġ√
                              ġ√ group on alphabets
     ṁ                           map and concatenate with:
      ?                            if:
                            Λ√      the group is alphabetical
       I                             leave as is
        ȯ`:'}+"^{"ṁos€"¹..⁹"        otherwise:
                  ṁȯ                  map and concat each char to:
                     €"¹..⁹"           index in ¹..⁹(0 if not present)
                    s                  cast to string
             +"^{"                    prepend "^{"
         `:'}                         append '{'
`JD;"¦$"                            surround the final string with "\$"
                     
```
[Answer]
# [Factor](https://factorcode.org/), ~~148~~ ~~92~~ ~~77~~ 70 bytes
```
[ nfkd R/ \d+/ [ "^{""}"surround ] re-replace-with "\\$%s\\$"sprintf ]
```
It doesn't work on TIO because TIO is missing `nfkd` which is perfectly extant in a proper copy of 0.98. So have a screenshot of running the quotation in the listener.
[![enter image description here](https://i.stack.imgur.com/aiEEJ.png)](https://i.stack.imgur.com/aiEEJ.png)
## Explanation:
It's a quotation (anonymous function) that takes a string from the data stack as input and leaves a string on the data stack as output.
* `nfkd` Convert a string to normalization form KD. (Turn `"²"` into `"2"`, for example.)
* `R/ \d+/` A regular expression that matches numbers.
* `[ "^{""}"surround ] re-replace-with` Replace numbers with themselves surrounded by `^{...}`.
* `"\\$%s\\$"sprintf` Surround the result with `\\$`.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~65~~ 59 bytes
```
~c{{∧"⁰¹²³⁴⁵⁶⁷⁸⁹"},?XdX&|{~h.↰₂i}ᵐtᵐcṫ,"}^{"↻↻}ᵐ{,"\$"↔}ⁱ²c
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wvy65uvpRx3KlR40bDu08tOnQ5keNWx41bn3UuO1R4/ZHjTseNe5UqtWxj0iJUKuprsvQA@tuyQTpLQHi5Ic7V@so1cZVKz1q2w1EIPFqHaUYFSB/Su2jxo2HNiX//x@tVKGko1RRWQUiD22CkId2QujKKohIJdD@nWAVQCdAKKAbNijFAgA "Brachylog – Try It Online")
:/
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~92~~ 89 bytes given that no constant(\$2x^3\$)
```
x=>`\\$${[...x].map(c=>c=='¹'?1:escape(c).slice(-1)).join``.replace(/\d+/g,'^{$&}')}\\$`
```
[Try it online!](https://tio.run/##XZBBasMwEEX3OYUXopZoI1chdJGi9AiFbqMYCUVJHBzLxKbINl7kRqWUgrc6Si7iKnZpHc9u/rz5M/yDeBeZPEVpPk30RrVb2hq65IwBUK0wxmaNjyKFki4lpb5t/BeyUJkUqYIS4SyOpIJTghA@6CjhHJ9UGgunBWxzH@we/LACd7WPamfI22c@Md5/MWAYmJiiHCpFedXs5w0WVrOaAe/1rWtmPWGbEULqflCUf@u/u0U5cnBC51LYxjbl4HpYEVJ3L1zOX6Mf5gOHeY98X84ft9DTo6O4Cy2XexiEq9BjydpFcURdkLkLUieZjhWO9Q5uYY4Qan8A "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), ~~99~~ 94 bytes
```
x=>`\\$${x.replace(/[~-⁹]+/g,s=>`^{${[...s].map(c=>c=='¹'?1:escape(c+c)[5]).join``}}`)}\\$`
```
[Try it online!](https://tio.run/##XZDRaoMwFIbv@xReBJrQNc7S7WLD7hEGuzVKQpp2LdZIlaGGDHyjMcbA2zyKL@JSHZv13J3/fOc/h//I3ljGz4c0XyZyK7qd3xX@hhICgCrwWaQx4wK6wfuyrZtw4e5vMjuOFFABxjgL8YmlkPsb7vtz08yfvAeRcZYKyBccBXchwkd5SCjVmiJtXWn3SGeF818EFATMirIaK2V10cznFRaplSbAeX7pm9VAmGaCeHoYlNXf@u9uWU0crNC7lKYxTTW6HinP0/0Lbf01@WE9clgPyHdbf1xD97eWojabnL9CNwoihySX8E6ozyu3eckkk7HAsdzDHcwRQt0P "JavaScript (Node.js) – Try It Online")
# ~~76~~ 71 bytes if allowed
```
x=>`\\$${x.replace(/[~-⁹]/g,c=>`{}^${c=='¹'?1:escape(c+c)[5]}`)}\\$`
```
[Try it online!](https://tio.run/##XY7RToMwFIbv9xRcNFmbbSDL3IWG@Qgm3lIamtqhhgEZxLQlNeGNjDEmveVReBGsYJRx7s7/f/9/zgt9pSU7PxfVJssfeX8MehEcYowBqIV75kVKGYde@LbpGhN5yZpZt9YE1CwIlq1Z3vk3vGS04JCtGAqvIx0jbeNxfxsvhPM/GAgMFkKqqSLVj9Z@XGCk3moMnPuHYdmORGtmiK9HQ6q/@G9WqlmDFYYW2ZrWqMl1Uvu@Hl7oms/ZD7tJw25Evrrm/RLaX1kqdk@0Yk/QIyFxcBatvOSErFbAKjiwPCvzlLtpnsAjrBBC/Tc "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~67~~ 61 bytes
```
->s{'\$'+s.unicode\_normalize(:nfkd).gsub(/\d+/,'^{\0}')+'\$'}
```
[Try it online!](https://tio.run/##KypNqvyfpmCrEPNf1664Wj1GRV27WK80LzM5PyU1Pi@/KDcxJ7MqVcMqLy07RVMvvbg0SUM/JkVbX0c9rjrGoFZdUxukp/Z/QWlJsUJatEp8rEJ5RmZOqkJ6aknx/4rKQ5sObT6081HjhqpHjVseNW5NedS47VHj9keNOx417gQA "Ruby – Try It Online")
`unicode_normalize(:nfkd)` seems quite long, but turns out to be 4 bytes shorter than `tr('⁰¹²³⁴-⁹','0-9')`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 38 bytes
```
ØJiⱮ_81»48Ọ⁾^{;;”}
O>Ø⁷Œgṁ@µ¹Çƭ€⁾\$,ṁ3
```
[Try it online!](https://tio.run/##AWsAlP9qZWxsef//w5hKaeKxrl84McK7NDjhu4zigb5eezs74oCdfQpPPsOY4oG3xZJn4bmBQMK1wrnDh8at4oKs4oG@XCQs4bmBM////2F6wrnCssKz4oG04oG14oG24oG34oG44oG54oGwYsKyYw "Jelly – Try It Online")
-4 bytes thanks to Jonathan Allan ("subtract 81, max with 48" is shorter than "logical OR 129, subtract 81") (prepend `\$` and mold like 3 is shorter than prepend `\$` + append `\$`) (2-byte built-in for 128 saves a byte)
Unfortunately I can't generate a test suite for this because `tie` will keep cycling, which causes various issues.
Might add explanation later after golfing (if I do either). TL;DR, groups by superscripts and non-superscripts, the applies the last link to every other element using tie-each, and the last link indexes into jelly's codepage, which contains ^1 through ^9, uses `or` to fix the lack of ^0 (absent items have index 0 since jelly is 1-indexed), subtract the offset, turn back to `chr`, and then apply formatting
[Answer]
# [Raku](http://raku.org/), 35 bytes
```
{'\$'~S:g/\d+/^\{$/}/~'\$'}o~*.NFKD
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Wj1GRb0u2CpdPyZFWz8uplpFv1a/DiRYm1@npefn5u3y31qhOLFSQUklXsHWTqE6TUElvlZJIS2/SMGmQqGiskqh4tAmED60E0RWVoF4lYd2HtoJlHnUuAVEbHvUuMHuPwA "Perl 6 – Try It Online")
This expression is the composition of two functions with the `o` operator. The right-hand function (the first to be applied) is `~*.NFKD`, which calls the `NFKD` method on its argument, then stringifies it, which turns superscript numbers into regular numbers. The left-hand function (between the brackets) constructs the final string by prepending and appending `\$` and using a regex to replace sequences of consecutive digits with `^{digits}`.
[Answer]
# [Python 3](https://docs.python.org/3/), 169 bytes
```
def k(s):
 g="¹²³⁴⁵⁶⁷⁸⁹⁰";h="\$"
 for y,x in enumerate(s):
 if s[y]in g:h+='^{'+x;continue
 if(x not in g)and(s[y-1]in g):h+='}'
 h+=x
 return h+'\$'
```
[Try it online!](https://tio.run/##JYxLCsIwFEXnXcUjCEmoDsSZ0pX4gappG8SXElNIFAfZkfh32qVkIzXW2b3cc27tTKVw0mFGrDsGf8/XG9JtRQE7duDTBMqMtJ/22t7iFvwj@Gfwr@DfwX@Cv5BZlZHFgCRQKA1uaEEiCGz2QudG/B9AFnCYu2VcymmVZnR1oqmdbRQaiY3oAWYBlfnJJc9xyyI/GvcG75UzjVgMNgEtTKMxFroY0K7WEg3bMeS8@wI "Python 3 – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 170 bytes
```
func[a][s: charset extract t:"⁰0¹1²2³3⁴4⁵5⁶6⁷7⁸8⁹9"2
parse a[any[any[not s skip]ahead s insert"^^{"any[change
set c s(t/:c)]insert"}"]]rejoin["\$"a"\$"]]
```
[Try it online!](https://tio.run/##RY9LTsMwEIb3PsVoxKKsKC2PkmN0a1zJchwSHo5lG6lp1YVvhAoUvPVRfJHglEJG8vgbzYz@f4ws@6UsKSNVAX31qgTljNoCRM2NlQ7k2hkuHLgCk3@bxnAZ97P4Pk/@4yr5z@vkDzfJf90m/71IPtzhjOhhEzjlqjs@1TqwYJ8azXgteZmLRllpHK5WWxwmsph6kGTQE2An7qIQ5@w0s0PGjHxsG0Xx/gz5kBjrq9ZILursTxugBHLgGk9/t/mjuB8phpG7zdjpYojhfyMfNuIh34yEUW0a5ajO3l/a5/JXdAHVEbKZHw "Red – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~245~~ 241 bytes
```
def m(a):
	b='⁰¹²³⁴⁵⁶⁷⁸⁹';r=c=0;o='\\$'
	for l in a:
		if l in b:
			n=str(b.index(l))
			if not r:o+='^{'+n;r=1
			elif r:o+=n
			if c==len(a)-1:o+='}'
		elif l not in b and r:o+='}'+l;r=0
		else:o+=l
		c+=1
	return o+'\\$'
```
[Try it online!](https://tio.run/##LY9LagMxDIbXk1N4UZCNSUnoLsE3CYV5eOiAIwePA0lDFr5RaV6d7RzFF5nKTnbWr8@fpN3Rf1n8mKZGt2zLS7GaFZWCGH7GYfwdLzFcY7jFcI/hEcNfDAOsnarVYm0VbDZvMCta65hhHbKS/hZd@yyqVBSoeu949d5how/cCJFCQtB65lZWKvg8gURSLlNHG@rlHF9grZTRSHvNlxk/08AnZrIkTWIlNi/bGaQh2SJDvU6ZoXctk99pv3fIrMyLTzvXoedbDofx0h/p3OGbri0rEGL6Bw "Python 3 – Try It Online")
-4 bytes thanks to pxeger.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 36 bytes
```
T`⁰¹²³⁴-⁹`d
\d+
{$&}
^|$
\$
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyThUeOGQzsPbTq0@VHjFt1HjTsTUrhiUrS5qlXUarnialS4YlT@/6/gqqis4qo4tAmED@0EkZVVIF4lUOtOoAxQL4jYBjQMAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
T`⁰¹²³⁴-⁹`d
```
Convert the superscripts to digits. (The `¹²³` cost 2 bytes each and the `⁰⁴⁹` cost three bytes each.)
```
\d+
{$&}
```
Wrap the superscripts in `{}`s.
```
^|$
\$
```
Wrap the entire string in MathJax tags.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes
```
\$Ｆ⁺Ｓ\$¿›ιz⊞υＶι«∧υ⪫{}⪫υωι≔⟦⟧υ
```
[Try it online!](https://tio.run/##LYy9DoIwFIVneYqbxuE2wSdwYjBGpyaO4tBggSZNMf1BhfBSbK68WG0D2znf@XKqlpuq4yoEZqR2SMpyT@gxqzsDyJS3eNEv724urg3SHFaBgqwBz0ZwJwzKiIcEmbct@hxOPVcoafwRygoYs936Xuhnmq@d1EjGiWwxojelSd88mWJhrWw03h85@NinED7f5bfMwzKHQ6/@ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
\$
```
Print the leading MathJax tag.
```
Ｆ⁺Ｓ\$
```
Append the trailing MathJax tag to the input string. This ensures that a subscript is not the last character in the loop.
```
¿›ιz
```
If the current character is greater than a `z`, then...
```
⊞υＶι
```
... evaluate it as a Charcoal digit and push the result to the predefined empty list.
```
«
```
Otherwise,
```
∧υ⪫{}⪫υω
```
If there is a superscript to print, then join the digits together and wrap them in `{}`s.
```
ι
```
Output the next character.
```
≔⟦⟧υ
```
Clear any superscript.
[Answer]
# [PHP](https://php.net/), ~~75~~ 73 bytes
```
fn($a)=>preg_replace('/\d+/','^{$0}',normalizer_normalize("\\$$a\\$",8));
```
<https://3v4l.org/mJZKd>
Works with PHP 7.4+ with the intl extension, doesn't work on TIO.
8 is the value of the `Normalizer::FORM_KD` constant, so this converts superscript characters to digits using NFKD.
[Answer]
# [Zsh](https://www.zsh.org/) `--extendedglob`, ~~121 116~~ 67 bytes
*Saved **a lot** by enabling extendedglob for the `(#m)` and `##` glob specs.*
```
<<<${1//(#m)[^a-z]##/^\{${MATCH//(#m)?/$[c=#MATCH,c-185?c&15:1]}\}}
```
~~[Try it online (has old comments)](https://tio.run/##jVPLbtNAFN37K45kq7abNsJAoOQBYoPUNWJDSCp7MsEDjsfyOLSN5YX/qGrpI9t8in8k3HFelUKhlq5n5s7cc899zVS4HDuusxzLFAyOlTuq3Xa9wmW@4rAY8r5/PBu4Qd8yVcMbNHoW63QOXUXnQJ/6Jjv2TlofTHbgtdreoFMYqkc4qjHMraEqCtfodrv2N8sm7B@EHbSHpNaKpWsYY1ws5ovrxU1V/q7K26q8q8r7qnyoynlVXulrLZez@uE1Vstivll3P4I6Y3Iy4XHGRxSRYZj4REFxn4VgoZ/6LOOpsRcncgMw8VWFtoIKZZqdRVImCjLJhIzhR5E8V8hRYMQjMRGEolDDUIbIdpso2gOrbNVbDfsxSXg8QhbyHQdkslZEQmWQYwQEoLYWXwitfj5NU4oFEY@/Z6F@p7VqmpB7lookW9k7VBZXI444QU9EvLIW8YhfrDEfl26t6nTqzeHfiUryzDLE00mwz/YRg@eS1gFu2Qb/YftkY2k/WjmAUGueI55IEWcbP2ORko9dnkm9jfgfn4nFHNRbixtQE5LcktyR3JM8kMxJrtB7D5PhAF5Lb9/Bw0u8wmu08AZvcUKaF8/x9VniXDcDZz8hNEEdDhFwRJM323AcctLrgSJ3XV2ewiiok0/H2ir0f3H48SUVIViX4AgpTyKf8VWjWzziegQ2Kamzfi6oFvYwtze3dmHvDSklN5@JhIZT26jiiBzV/RCjHltKtD5Nmk@Os2G4yz8 "Zsh – Try It Online")~~
[Try it online!](https://tio.run/##qyrO@F@cWpJfUKKQWlGSmpeSmpKek5/ElaahqfHfxsZGpdpQX19DOVczOi5RtypWWVk/LqZapdrXMcTZAyJhr68SnWyrDBbRSdY1tDC1T1YzNLUyjK2Nqa39r8nFlaZQcWjnoU2HNj9q3PKoceujxm2PGrc/atzxqHHno8YNIGkQrqwCK9ykAKEO7YTRCOI/AA "Zsh – Try It Online")
```
${1//$find/$repl}  # replace all instances of $find with $repl
[^a-z]##           # The glob [^a-z]## is equivalent to the regex [^a-z]+
(#m)[^a-z]##       # Set $MATCH to the value matched by [^a-z]]##
(#m)?              # "?" matches any single character
$[$e1,...,$en]     # $[arithmetic substitution], substitutes the result of $en
c=#MATCH           # Set c to the codepoint of the first character of $MATCH
c&15               # ¹ ² ³ ⁴ ⁵ ⁶ ⁷ ⁸ ⁹ ⁰ => #c & 15 => 9 1 2 3 4 5 6 7 8 9 0
c-185?c&15:1       # If $MATCH is ¹ (codepoint 185), output 1, else codepoint & 15
<<<$str            # prints $str to stdout
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 60 bytes
```
s=>`\\$${s.replace(/\W+/g,n=>`^{${n.normalize`NFKD`}}`)}\\$`
```
[Try it online!](https://tio.run/##XY6xTsMwFEX3fIUHD7EKDqkqliqdgAUJJBhYrMiW64SixK7iCCW2PPSPEEJIWfMp/ZGQJgjSvO3dd@599429M82L3b68lGoruiTqdLShhEBoNS7EPmNc@AF5WQTphewvsYVWYqmKnGU7I@jD3f0NdY4i13toVwpdcqaFBhGgXgX@h8CKQK@qzVSpzUlrP8@w2C4dgeDxaViWI9E2MyR046E2f/Zfb21mCb0wpNRt0zZm8j22YeiGCsfD16zDapKwGpHv4@HjHLq@OrWgOGclf/WDmDwvgjxFOFHFLesVCaINsB4AXEmtMoEzlfqJLxFaew6tux8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 34 bytes
```
"⁰¹²³⁴⁵⁶⁷⁸⁹"S9Ý€"^{ÿ}":„\$.ø…}^{õ:
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f6VHjhkM7D206tPlR45ZHjVsfNW571Lj9UeOOR407lYItD8991LRGKa768P5aJatHDfNiVPQO73jUsKwWKLTV6v//CrD6DQA "05AB1E – Try It Online")
## Explained:
```
"..."S                        # Push [⁰...⁹]
      9Ý                      # Push [0...9]
        €"^{ÿ}"               # Surround each element of [0...9] with ^{ }
               :              # Replace each element of [⁰...⁹] with its counterpart in [^{0}...^{9}]
                   .ø         # Surround input with...
                „\$           # \$ \$
                          :   # Replace...
                     …}^{     # instances of  "}^{"
                         õ    # with an empty string
```
]