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?
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(/[\\\\]$/, '\\\\')}`);
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());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.