Replace double backslashes with a single backslash in javascript

Guido Visser picture Guido Visser · Aug 14, 2014 · Viewed 16.4k times · Source

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?

Answer

KooiInc picture KooiInc · Aug 14, 2014

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

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