Replace double backslashes with a single backslash in javascript Replace double backslashes with a single backslash in javascript ajax ajax

Replace double backslashes with a single backslash in javascript


This should do it: "C:\\backup\\".replace(/\\\\/g, '\\')

In the regular expression, a single \ must be escaped to \\, and in the replacement \ also.

[edit 2021] Maybe it's better to use 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 themselvesconsole.log(`Double escaped ${`C:\\\\backup\\\\`.replace(/\\\\/g, '\\')}`);// don't want to replace the second \\console.log(`not the second ${`C:\\\\backup\\\\`.replace(/\\\\/, '\\')}`);// don't want to replace the first \\console.log(`not the first ${`C:\\\\backup\\`.replace(/[\\]$/, '\\')}`);