简体   繁体   English

JavaScript:将字符串文字转换为字符串

[英]JavaScript: convert string literal to string

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).所有可能的转义字符的列表非常短(可能是 7 或 8 个字符)。 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.请注意, eval不仅速度慢,而且在用于未经检查的字符串时也非常危险。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM