sra1
sra1

Reputation: 93

How to pass a string variable to String.raw in javascript?

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}`

Upvotes: 5

Views: 6233

Answers (1)

Ivar
Ivar

Reputation: 6848

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

Upvotes: 2

Related Questions