簡體   English   中英

包含JavaScript中字符串文字的字符串

[英]String containing the literal of a string in JavaScript

我想編寫一個可以可靠地從JavaScript字符串獲取字符串文字的函數-我們可以將其稱為f

例如:

f('hello world') //-> 'hello world' (or "hello world")
f('hello "world"') //-> 'hello "world" (or "hello \"world\"")
f("hello 'world'") //-> "hello 'world'"
f("hello \"'world'\"") //-> "hello \\\"'world'\\\""
f("hello \n world") //-> "hello \\n world"

所以對於任何字符串str

str = eval(f(str))

我不太在乎單引號。

我目前正在做:

var f = function(str) {
  return '"' + str.replace(/"/g, '\"') + '"';
}

但這顯然不能涵蓋所有內容。


這是用於文檔系統的。

如果我正確閱讀了您的內容,該怎么辦?

var Map = {
    10: "n",
    13: "r",
    9:  "t",
    39: "'",
    34: '"',
    92: "\\"
};
function f(str) {
    var str = '"' + str.replace(/[\n\r\t\"\\]/g, function(m) {
        return "\\" + Map[m.charCodeAt(0)]
    }) + '"';
    print(str);
}

f('hello world') //-> 'hello world' (or "hello world")
f('hello "world"') //-> 'hello "world" (or "hello \"world\"")
f("hello 'world'") //-> "hello 'world'"
f("hello \"'world'\"") //-> "hello \\\"'world'\\\""
f("hello \n world") //-> "hello \\n world"

>>"hello world"
>>"hello \"world\""
>>"hello 'world'"
>>"hello \"'world'\""
>>"hello \n world"

使用phpjs的addslashes

function f(str) {
    return "\"" + addslashes(str) + "\"";
};

http://jsfiddle.net/Xeon06/vT3zv/

暫無
暫無

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

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