Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace double backslashes with a single backslash in javascript

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?

like image 534
Guido Visser Avatar asked Aug 14 '14 09:08

Guido Visser


People also ask

How do you replace a double backslash with a single backslash?

Use the str. replace() method to replace a double backslash with a single backslash, e.g. new_string = string. replace('\\\\', '\\') . Backslashes have a special meaning in Python, so each backslash has to be escaped with another backslash.

How do you write one backslash in Javascript?

As you stated, if you want a literal backslash in a string, you need to write two of them. "\\" is a single backslash. "\\\\" is two backslashes.

How do you replace a single backslash with double backslash in Java?

replaceAll("\\\\", "\\\\\\\\")); would work if you want to use replaceAll . If you want to use replaceAll try this: 'System. out. println(s.

How do you change a forward slash with a backward slash?

Press \\ to change every forward slash to a backslash, in the current line.


1 Answers

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(/[\\]$/, '\\')}`);
like image 193
KooiInc Avatar answered Sep 25 '22 13:09

KooiInc