在Javascript中将双反斜杠替换为单个反斜杠

19

我有以下问题:

我有一个脚本,执行 AJAX 请求到服务器,服务器会在预览中返回C:\backup\。然而,响应实际上是"C:\\backup\\"。这并不是什么大问题,因为我只需将双斜杠替换为单个斜杠。我在 Stack 上找过,但只能找到如何将单个反斜杠替换为双个反斜杠的方法,但我需要相反的操作。

有谁能帮我解决这个问题吗?

3个回答

34
这应该可以: "C:\\backup\\".replace(/\\\\/g, '\\') 在正则表达式中,单个\必须转义为\\,在替换中\也是如此。
[编辑2021] 也许最好使用模板文字

console.log(`original solution ${"C:\\backup\\".replace(/\\\\/g, '\\')}`)

// a template literal will automagically replace \\ with \
console.log(`template string without further ado ${`C:\\backup\\`}`);

// but if they are escaped themselves
console.log(`Double escaped ${`C:\\\\backup\\\\`.replace(/\\{2,}/g, '\\')}`);

// multiple escaped
console.log(`multiple escaped ${`C:\\\\\\\\backup\\\\`
  .replace(/\\{2,}/g, '\\')}`);

// don't want to replace the last \\
console.log(`not the last ${`C:\\\\\\backup\\\\`
  .replace(/\\{2,}([^\\{2,}$])/g, (a ,b) => a.slice(0,1) + b)}` );

// don't want to replace the first \\
console.log(`not the first ${`C:\\\\backup\\`.replace(/\\[^\\]$/g, '\\')}`);

// a generic tagged template to replace all multiple \\ OR //
const toSingleSlashes = (strs, ...args) => 
  strs.reduce( (a, v, i ) => 
    a.concat(args[i-1] || ``).concat(v, ``), `` )
      .replace( /(\\|\/){2,}/g, (a, b) => b );

console.log(`generic tagged template 1 ${
  toSingleSlashes`C:\\backup\\`}`);

console.log(`generic tagged template 2 ${
  toSingleSlashes`C:\\\\\\\\backup\\\\\\\\\\`}`);
  
console.log(`generic tagged template 3 ${
  toSingleSlashes`C:\\\\\\\\backup\\`}`);
  
console.log(`generic tagged template 4 ${
  toSingleSlashes`C:////////backup////`}`);

console.log(`reply to comment @chitgoks => 
"test\\\\hehehe" is by default "test\\hehehe"
so, no replacement necessary here ...`);
.as-console-wrapper {
    max-height: 100% !important;
}


1
很高兴能帮助到你(niks te danken;) - KooiInc
这也将删除任何单斜杠 'ab\cd' --> abcd - codemirror
我在原始正则表达式中有两个双反斜杠,当进行转义时会变成四个反斜杠。现在,当我尝试使用你的正则表达式时,它将这四个反斜杠转换为单个反斜杠而不是双反斜杠。我该怎么做才能避免这种情况发生? - HalfWebDev
@codemirror,您不需要任何替换:字符串ab\cd本身不会包含斜杠(\c = (escape)c)。在开发者控制台中尝试console.log("ab\cd") - KooiInc
'test\hehehe'.replace(/\\/g, '\') 不起作用。 - chitgoks
@chitgoks 请查看已编辑的答案(运行代码片段,查看日志底部)。 - KooiInc

4
最好使用正则表达式来替换所有出现的内容:
C:\\backup\\".replace(/\/\//g, "/")[0]

这将返回:C:\backup\

或者使用split()

"C:\\backup\\".split();

请确保备份文件夹路径为 C:\backup\,以便产生您所需的结果。

console.log("using \"C:\\backup\\\".replace(/\/\//g, \"/\")")
console.log("C:\\backup\\".replace(/\/\//g, "/"));

console.log("Using \"C:\\backup\\\".split()");
console.log("C:\\backup\\".split()[0]);


只想指出这将使用正斜杠而不是反斜杠。 - Sami Fouad
这也将删除任何单斜杠 'ab\cd' --> abcd - codemirror
1
@codemirror 很好的观点。但是如果它包含 '',那么你在代码中看到的不会是 'ab\cd',而是 'ab\cd'。 - xxbinxx
你的代码片段 "C:\\backup\\".split(); 在Chrome控制台测试时无法正常工作。此外,更恰当的做法是写成 "C:\\backup\\".split()[0] 直接获取所需的字符串。 - Pieber

0
我认为每个人可能都对console.log()有误解。它会自动显示预期的结果,无论您是否替换任何字符。
const test = 'C:\\';
console.log( test ) // this will write out "C:\"
console.log( `${ test.replace( /\\{2,}/g, '\\' }` ) // this will also write out "C:\"

字符串值仍然是单个字符转义的。然而,console.log将这一事实隐藏起来。
据我所知,在javascript中没有办法真正地用\替换\\
你能做到的最接近的方法可能是像这样做,但它仍然以相同的方式解释。
test.replace( /\\{2,}/g, '\u005C' )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接