Replace double backslash with single backslash in javascript

I have the following problem:

I have a script that makes an AJAX request to the server, the server returns C:\backup\

in a preview. However the answer is "C:\\backup\\"

. Not a big deal since I just decided to replace double slashes with single ones. I'm looking around here on the stack, but I could only find how to replace single backslashes with doubles, but I need it the other way around.

Can anyone help me with this issue?

+3


source to share


2 answers


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



In a regex, a single \

must be escaped before \\

and also in replacement \

.

+9


source


Your best bet is to use regex to replace all occurrences:

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

      

this returns: C:\backup\

OR

use split ()



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

      

both give the 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());
      

Run codeHide result


+2


source







All Articles