How to use String.raw on array variables

Viewed 1012

I have a problem in my code, i have defined arrays but it contain special characters like /, {}, (), [], etc... (because of plainsource MathJax)

The array returns the string without those mentioned special characters

PS: I've read about String.raw but i have no idea how to use it in this kind of array. Help me please :(

var Array_QA = {
    "\Large {\lim_{x \to 2}} (5^x + 2^x + 4)" : "33",
    "\Large {\lim_{x \to 2}} \frac {x^2 - 6x + 8}{x^3 - 4}" : "0"
};
2 Answers

Because the backslash is an escape character in javascript strings, you need to double it if you want it to appear in a string literal. Try

var Array_QA = {
    "\\Large {\\lim_{x \\to 2}} (5^x + 2^x + 4)" : "33",
    "\\Large {\\lim_{x \\to 2}} \\frac {x^2 - 6x + 8}{x^3 - 4}" : "0"
};

String.raw is used with template literals, the new(ish) ES6 syntax for strings with interpolated variables, embedded quotes and newlines, and the optional application of "tags" (which are just function callbacks that receive the pieces of the template split up by each interpolated variable to return the final combined string however you like).

So if I have a function that processes a template literal, and it's called processLiteral, then I could do something like this to apply it to a literal:

processLiteral`This is a string with interpolated variables like ${someVar} and also ${otherVar}.`

Specifically, String.raw is meant to be used as the tag of a template literal, and it will return the raw string without processing any escaped characters. Meaning \n will remain as \n and not become a newline, \t will remain as \t and not become a tab, etc. It does this by automatically adding slashes before any escaping slashes, thereby escaping them, so it's equivalent to using \\n, \\t, etc.

So in your case, if you want to use that method, since you can't put template literals directly in an object key declaration (it doesn't parse correctly), you'd do something like this:

var Array_QA = {};
Array_QA[String.raw`\Large {\lim_{x \to 2}} (5^x + 2^x + 4)`] = "33";
Array_QA[String.raw`\Large {\lim_{x \to 2}} \frac {x^2 - 6x + 8}{x^3 - 4}`] = "0";

That said, having complex strings like that as object keys is probably not a good idea from the start... but it should work. I'd suggest refactoring your code to do that differently, if you can.

Related