在javascript中将双反斜杠替换为单反斜杠

5gfr0r5j  于 2023-02-07  发布在  Java
关注(0)|答案(2)|浏览(518)

我有以下问题:
我有一个脚本,执行一个AJAX请求到服务器,服务器返回C:\backup\在预览。然而,响应是"C:\\backup\\"。不是真的有什么大不了的,因为我只是想取代双斜线与单。我一直在寻找这里的堆栈,但我只能找到如何取代单反斜线与双,但我需要它的其他方式。
有人能帮我处理这件事吗?

anauzrmj

anauzrmj1#

这应该可以做到:"C:\\backup\\".replace(/\\\\/g, '\\')
在正则表达式中,单个\必须转义为\\,在替换\中也是如此。
[edit 2021]也许使用template literals更好。

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;
}
cclgggtu

cclgggtu2#

最好是使用regex替换所有出现的内容:

C:\\backup\\".replace(/\/\//g, "/")[0]

这将返回:C:\backup\

使用拆分()

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

都能产生你想要的结果
C:\备份\

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]);

相关问题