使用RegEx将单个反斜杠替换为字符串中的双反斜杠

时间:2014-02-13 00:06:43

标签: javascript string

我需要你的帮助。

如何从以下字符串转换以下字符串:

var x =“A:\ V10 \ db \”

为:

var x =“A:\\ V10 \\ db \\”

请注意,双引号也构成字符串的一部分。

我尝试了以下但没有成功:

function test() {

var dbPath  =   "A:\V10\db"

dbPath = dbPath.replace(/\\/g, dbPath)

alert(dbPath)

}

1 个答案:

答案 0 :(得分:0)

反斜杠是escape character,(link two)。如果你使用它,你也必须逃避它。

示例:

var x = "foo\"bar"; // Here we escape double-quote as the string is enclosed by "
var x = 'foo\'bar'; // Same thing with '

示例导致文字字符串

foo"bar
foo'bar

如果要在字符串中使用反斜杠,则必须使用反斜杠或使用例如十六进制表示法。例如:

var x = "foo\\bar";    // Escaping backslash.
var x = "foo\x5cbar";  // Using hex escape sequence.

这些示例都会产生文字字符串:

foo\bar

现在要获得两个反斜杠字符,你可以逃脱,每两个字母给我们四个。

var x = "foo\\\\bar";
var x = "foo\x5c\x5cbar";

这些示例都会产生文字字符串:

foo\\bar

现在,在那之后,用double替换单个反斜杠应该是微不足道的:

x = x.replace(/\\/g, '\\\\');
    |          |  |    |
    |          |  |    +----- With two back-slashes. (both escaped.)
    |          |  +---------- Replace globally (all).
    |          +------------- Replace single backslash (and as usual escape it)
    +------------------------ The string variable

其他转义序列:

反斜杠不仅用于转义引号或反斜杠,还用于表示特殊控制字符和转义序列 - 参考。顶部的链接。除了我们已经使用的\xNN之外,例如:

\n  Newline
\t  Tab

所以给出了这个陈述:

var x = "Some\nDay\tWe are\ngone.";

结果是字符串:

Some<NEW LINE>
Day<TAB>We are<NEW LINE>
gone