I'd like to write a function that works reliably to get the string literal from a JavaScript string---we can call it f
.
For example:
f('hello world') //-> 'hello world' (or "hello world")
f('hello "world"') //-> 'hello "world" (or "hello \"world\"")
f("hello 'world'") //->开发者_Go百科 "hello 'world'"
f("hello \"'world'\"") //-> "hello \\\"'world'\\\""
f("hello \n world") //-> "hello \\n world"
And so for any string str
str = eval(f(str))
I don't care about the single quotes thing too much.
I currently am just doing:
var f = function(str) {
return '"' + str.replace(/"/g, '\"') + '"';
}
but that obviously doesn't cover everything.
This is for a documentation system.
If I've read what your after correctly, how about;
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"
Using phpjs's addslashes:
function f(str) {
return "\"" + addslashes(str) + "\"";
};
http://jsfiddle.net/Xeon06/vT3zv/
精彩评论