14

I have the following problem:

I have a script that executes an AJAX request to a server, the server returns C:\backup\ in the preview. However, the response is "C:\\backup\\". Not really a big deal, since I just thought to replace the double slashes with single ones. I've been looking around here on stack, but I could only find how to replace single backslashes with double ones, but I need it the other way around.

Can someone help me on this matter?

Guido Visser
  • 2,005
  • 5
  • 25
  • 39

2 Answers2

28

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 themselves
console.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(/[\\]$/, '\\')}`);
KooiInc
  • 112,400
  • 31
  • 139
  • 174
  • 1
    Glad I could help (niks te danken;) – KooiInc Aug 14 '14 at 09:15
  • This will also remove any single slash 'ab\cd' --> abcd – codemirror Sep 12 '17 at 11:20
  • I have double backslash in original regex which when escaped boils down to four backslashes. Now, when I tried your regex, it converts those four backslashes to single backslash instead of double. What can I do to prevent it? – HalfWebDev Aug 07 '19 at 05:49
  • @codemirror you don't need any replacement: the string `ab\cd` itself will not contain a slash, (\c = (escape)c). Try `console.log("ab\cd")` in the developer console. – KooiInc Apr 19 '21 at 15:44
4

Best is to use regex to replace all occurrences:

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

this returns: C:\backup\

OR

use split()

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

both produces your desired result

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());
xxbinxx
  • 1,437
  • 10
  • 17