我有以下问题:
我有一个脚本,执行 AJAX 请求到服务器,服务器会在预览中返回C:\backup\
。然而,响应实际上是"C:\\backup\\"
。这并不是什么大问题,因为我只需将双斜杠替换为单个斜杠。我在 Stack 上找过,但只能找到如何将单个反斜杠替换为双个反斜杠的方法,但我需要相反的操作。
有谁能帮我解决这个问题吗?
我有以下问题:
我有一个脚本,执行 AJAX 请求到服务器,服务器会在预览中返回C:\backup\
。然而,响应实际上是"C:\\backup\\"
。这并不是什么大问题,因为我只需将双斜杠替换为单个斜杠。我在 Stack 上找过,但只能找到如何将单个反斜杠替换为双个反斜杠的方法,但我需要相反的操作。
有谁能帮我解决这个问题吗?
"C:\\backup\\".replace(/\\\\/g, '\\')
在正则表达式中,单个\
必须转义为\\
,在替换中\
也是如此。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;
}
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]);
"C:\\backup\\".split();
在Chrome控制台测试时无法正常工作。此外,更恰当的做法是写成 "C:\\backup\\".split()[0]
直接获取所需的字符串。 - Pieberconsole.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
将这一事实隐藏起来。\
替换\\
。test.replace( /\\{2,}/g, '\u005C' )
ab\cd
本身不会包含斜杠(\c = (escape)c)。在开发者控制台中尝试console.log("ab\cd")
。 - KooiInc