24

I need to replace this path: C:\test1\test2 into this: C:/test1/test2

I am using jquery but it doesn't seem to work

var path = "C:\test1\test2";
var path2 = path.replace("\", "//");

How should it be done?

Roamer-1888
  • 19,138
  • 5
  • 33
  • 44
manuel_k
  • 575
  • 1
  • 8
  • 22

2 Answers2

64

You have to escape to backslashes.

var path = "C:\\test1\\test2";
var path2 = path.replace(/\\/g, "/");
console.log(path2);
Toto
  • 89,455
  • 62
  • 89
  • 125
  • 1
    how can we do for '\' single backslash to forward '/'? – Code_S Jan 14 '21 at 10:11
  • @Code_S: My answer is working for a single backslash. But, because you have to escape the backslash with another backslah, you have 2 backslashes in the regex. – Toto Jan 14 '21 at 10:19
  • 2
    var path = "C:\test1\test2"; var path2 = path.replace(/\\/g, "/"); console.log(path2); It is not working and I have tried , could you let us know how could it be done. Thanks – Code_S Jan 14 '21 at 10:37
  • @Code_S: You also have to escape the backslash in the string `var path = "C:\\test1\\test2";` As you can see, it works when you run the code snippet. – Toto Jan 14 '21 at 11:15
  • 1
    It works in the snippet because there are two backslashes and not only one like asked in the question – PierBJX Apr 27 '22 at 15:14
  • @PierBJX: There are double backslashes in the string because backslash have to be escaped. If you print the string, you will get `C:\test1\test2`. Test it. – Toto Apr 27 '22 at 15:35
  • Yes, I agree but it does not answer the question at the end. Why it does not work if you do directly `'C:\test1\test2'.replace(/\\/g, "/")` ? – PierBJX Apr 27 '22 at 22:24
  • @PierBJX: Have you printed `path` when `var path = "C:\\test1\\test2";` and `var path = 'C:\test1\test2';`? The former gives `C:\test1\test2`, the later `C: est1 est2` where `\t` is replaced by a tabulation. Or you have to use `String.raw`. In the code snippet it is just a way to assign the value. – Toto Apr 28 '22 at 08:52
  • Yes yes I printed and I totally agree with you. It is just if you do it inline `'C:\test1\test2'.replace(/\\/g, "/")` like this it does not work. You have to use `String.raw` as you mentionned => String.raw ` C:\test1\test2 ` .replace(/\\/g, "/") – PierBJX Apr 28 '22 at 09:31
  • Just in-case someone ever gets this far and is still stuck. A single backslash can't be replaced, because it is automatically escaped before the replace can happen. However you can disable escaping like this: ```(String.raw`C:\test1\test2`).replace(/\\/g, "/")``` – Kodaloid Jul 05 '23 at 22:47
2

Your original string is in the wrong format, as '\t' inside it is for a tab symbol. Please change it (may be from the server side) to this:

    var path = "C:\\test1\\test2";

so your code could change to this:

    var path = "C:\\test1\\test2";
    var path2 = path.replace(/\\/g, '/');
Tommy Nguyen
  • 96
  • 1
  • 5