2011-10-11 35 views
1

JavaScript文字列から文字列リテラルを確実に取得する関数を記述したいと思います。fと呼ぶことができます。例えばJavaScript内の文字列のリテラルを含む文字列

:私はあまりにも多くの単一引用符の事を気にしない、任意の文字列str

str = eval(f(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" 

そしてそう。

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

をそれは明らかに、すべてをカバーしていない:

私は現在だけでやっています。


これはドキュメントシステム用です。使用

答えて

1

何あなたの後に正しく、方法については、

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" 
関連する問題