-1

I want to convert string literals to strings.

For example:

var stringLiteral="\\\" hi world \\\"";
console.log(stringLiteral) //outputs \" hi world \";
var string=convertStringLiteralToString(stringLiteral);
// ^ eval() would be perfect for this were it not horribly slow. <the cake is a lie, guys>
console.log(string); //outputs " hi world "

How could I write a function that does this?

Ben Rivers
  • 129
  • 10
  • 1
    This really sounds like an [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) - is there an underlying issue that's led you down this path? – James Thorpe Mar 21 '18 at 16:28
  • @JamesThorpe no, I'm trying to log all the strings found in a function (that has been converted into a string.), but at the moment it will log stuff like `the cake is a\\ lie` when I want it to log `the cake is a \lie` – Ben Rivers Mar 21 '18 at 16:41

1 Answers1

1

The list of all possible escaped characters is very short (maybe 7 or 8 characters). Your best option is a simple text replace.

string = string
    .replace('\\\"','\"')
    .replace('\\\\','\\')
    /* ... and so on */

Note that eval is not only slow, but also very dangerous when used against unchecked strings.

Mario Cianciolo
  • 1,223
  • 10
  • 17