Depending on the Markdown implementation math is either not supported at all -- or directly through the same syntax. Either way, it'd probably make most sense to simply keep $...$
expressions intact and not escape strings contained therein. While a simple filter for that would certainly work, MathJax allows supporting different escape characters than $...$
for inline- and $$...$$
for display-math, e.g., from the article https://math.andrej.com/2007/09/28/seemingly-impossible-functional-programs/:
<script>
window.MathJax = {
tex: {
tags: "ams", inlineMath: [ ['$','$'], ['\\(', '\\)'] ],
displayMath: [ ['$$','$$'] ],
processEscapes: true,
},
options: {
skipHtmlTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
},
loader: {
load: ['[tex]/amscd'] }
};
</script>
This would necessate parsing Js though ...