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 ...`);
2条答案
按热度按时间anauzrmj1#
这应该可以做到:
"C:\\backup\\".replace(/\\\\/g, '\\')
在正则表达式中,单个
\
必须转义为\\
,在替换\
中也是如此。[edit 2021]也许使用template literals更好。
cclgggtu2#
最好是使用regex替换所有出现的内容:
这将返回:
C:\backup\
或
使用拆分()
都能产生你想要的结果
C:\备份\