簡體   English   中英

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不僅速度慢,而且在用於未經檢查的字符串時也非常危險。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM