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

时间:2011-10-11 15:10:00

标签: javascript node.js

我想编写一个可靠的函数来从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, '\"') + '"';
}

但这显然不包括一切。


这适用于文档系统。

2 个答案:

答案 0 :(得分: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"

答案 1 :(得分:0)

使用phpjs's addslashes

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

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