JavaScript: 将字符串文字转换为字符串
JavaScript: convert string literal to string
我想将字符串文字转换为字符串。
例如:
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 "
我如何编写执行此操作的函数?
所有可能转义字符的列表非常短(可能只有 7 或 8 个字符)。最好的选择是简单的文本替换。
string = string
.replace('\\"','\"')
.replace('\\','\')
/* ... and so on */
请注意 eval
不仅速度慢,而且在用于未经检查的字符串时非常危险。
我想将字符串文字转换为字符串。
例如:
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 "
我如何编写执行此操作的函数?
所有可能转义字符的列表非常短(可能只有 7 或 8 个字符)。最好的选择是简单的文本替换。
string = string
.replace('\\"','\"')
.replace('\\','\')
/* ... and so on */
请注意 eval
不仅速度慢,而且在用于未经检查的字符串时非常危险。