1

I have an endpoint that returns back a string in a JSON, i.e.:

"<p>Rationalize the denominator of each expression. Write your answer in simplest form.</p><p><code class='latex inline'>\n\\displaystyle\n\\frac{\\sqrt{3}+\\sqrt{5}}{\\sqrt{2}}\n</code></p>"

When I try to use that string in JavaScript, it automatically converts it to:

"<p>Rationalize the denominator of each expression. Write your answer in simplest form.</p><p><code class='latex inline'> \displaystyle \frac{\sqrt{3}+\sqrt{5}}{\sqrt{2}} </code></p>"

The backslashes are gone as it reads it as an escape character instead of it being a part of the string. I need these backslashes to persist in the string, but I lose it before I can manipulate it in any way. What can I invoke to keep the string as it is originally?

averageUsername123
  • 725
  • 2
  • 10
  • 22
  • Why do you need the backslashes? – Unmitigated Jul 21 '20 at 00:36
  • 1
    JSON doubles the literal backslashes, parsing it converts them back to single backslashes. You shouldn't need to keep them. – Barmar Jul 21 '20 at 00:37
  • The whole point of serialization formats like JSON is that the result is the same as the original data. Don't fight it. – Barmar Jul 21 '20 at 00:38
  • I think following should answer your question: https://stackoverflow.com/questions/3903488/javascript-backslash-in-variables-is-causing-an-error – Maxqueue Jul 21 '20 at 00:39
  • @hev1 I'm using a library (katex) that requires the backslashes to exist in order to render the text. – averageUsername123 Jul 21 '20 at 00:41
  • `"

    Rationalize the denominator of each expression. Write your answer in simplest form.

    \n\\displaystyle\n\\frac{\\sqrt{3}+\\sqrt{5}}{\\sqrt{2}}\n

    ".replace(/\\/g, "\\\\");`
    – Unmitigated Jul 21 '20 at 00:44
  • @averageUsername123 Does that help? – Unmitigated Jul 21 '20 at 00:46
  • Sorry for the off-topic comment... but ... @Barmar Are you the same "barmar" I worked with at BBN who helped write portions of BIND 8? – Dshiz Jul 21 '20 at 01:12
  • @Dshiz I did work at BBN, although I wasn't involved in BIND 8 coding. – Barmar Jul 21 '20 at 01:24
  • @Barmar myth precedes legends, then. We used to refer to hearing from you as being "barmared" when it came to DNS related topics. :) – Dshiz Jul 21 '20 at 01:26
  • @hev1 `error Unnecessary semicolon no-extra-semi` Can you help explain what it is you're trying to do? A regex expression parameter to replace all "\" with "\\" ? – averageUsername123 Jul 21 '20 at 01:32
  • 2
    @averageUsername123 That looks like an eslint error which has nothing to do with hev1's code or the functionality of it. I guess you simply added an additional semicolon when you copy-pasted hev1's code. – Lennholm Jul 21 '20 at 01:43
  • @averageUsername123 Yes, it replaces all backslashes with two backslashes. – Unmitigated Jul 21 '20 at 02:47

0 Answers0