我需要你的帮助。
如何从以下字符串转换:
var x = "A:\V10\db\"
自:
var x = "A:\\V10\\db\\"
请注意,双引号也构成字符串的一部分。
我尝试了以下方法,但没有成功:
function test() {
var dbPath = "A:V10db"
dbPath = dbPath.replace(/\/g, dbPath)
alert(dbPath)
}
斜杠是一个转义字符,(链接二)。如果你使用它,你也必须逃避它。
例:
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 = "foox5cbar"; // Using hex escape sequence.
这些示例都生成文本字符串:
foobar
现在要获得两个反斜杠字符,您可以转义,每两个都给我们四个。
var x = "foo\\bar";
var x = "foox5cx5cbar";
这些示例都生成文本字符串:
foo\bar
现在,在那之后,用双反斜杠替换应该是微不足道的:
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 = "SomenDaytWe arengone.";
字符串中的结果:
Some<NEW LINE>
Day<TAB>We are<NEW LINE>
gone