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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.