Javascript 用正斜杠 (/) 替换反斜杠 (\)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42855606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:28:14  来源:igfitidea点击:

Replace back slash (\) with forward slash (/)

javascriptregex

提问by manuel_k

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

我需要将此路径替换C:\test1\test2为: C:/test1/test2

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

我正在使用 jquery 但它似乎不起作用

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

How should it be done?

应该怎么做?

回答by Toto

You have to escape to backslashes.

你必须转义到反斜杠。

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

回答by Tom Nguyen

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:

您的原始字符串格式错误,因为其中的 '\t' 用于制表符。请将它(可能是从服务器端)更改为:

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

so your code could change to this:

因此您的代码可以更改为:

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