5

I have a variable in which I have text written in latex format

let textVar ="$\frac{1}{2}$"
console.log(textVar)
"$rac{1}{2}"
console.log(String.raw`$\frac{1}{2}$`)
"$\frac{1}{2}$"

I lose my escape characters (\ + the next char) when I do console.log(textVar) I understand the functionality of escape charaters in text and I need to add double quotes (\\) inorder to retain them in textVar, which I cannot do

I found that String.raw`$\frac{1}{2}$` retains text without escaping.

Can I pass my textVar to String.raw in any way?

This doesn't work though String.raw`${textVar}`

1
  • No, template string syntax allows passing the raw string to tag functions, which String.raw makes use of. Once the string is assigned it is too late. The best you will be able to do is keep a list of latex commands and "fix" them at that point. Commented Jun 5, 2020 at 19:27

1 Answer 1

2

If you mean that your mentioned string literal is already assigned to textVar and you want to get the raw string that you entered in the string literal afterwards, then no, that is not possible.

Once the string literal is assigned to the variable, that information is lost.

If you cannot escape the backslashes in your string literal, the only option is to assign the String.raw directly to your textVar.

let textVar = String.raw`$\frac{1}{2}$`
console.log(textVar);

Sign up to request clarification or add additional context in comments.

17 Comments

If textVar is a field in post api body, how do I apply String.raw on it ?
Do you mean that you get this string from an AJAX request? If that's the case then non of this applies. You get the response already as a string instead of a string literal.
Yes, I'm getting a string from AJAX, but when i try to use this string for someother purpose in backend, I'm losing these escape characters
Then the JSON was not formed correctly and you should probably talk to the backend developers. If they used a standard JSON library to serialize, backslashes should have been escaped when serialized. Double check and look at the actual JSON response you get from the backend API and see if it is correct.
It isn't lost. You are copy/pasting decorated visual representations of the data that does not represent valid JavaScript (nor JSON) representations of the actual string. It is visualized that way only for convenience of the eye. JSON exists for a reason: proper serialization of data. Whatever it is you are doing to serialize the JavaScript data to a string is wrong. The output you should be using is from JSON.stringify(data), not some copy/paste of the data you get from the console.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.