javascript 在javascript中用单个反斜杠替换双反斜杠

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25304214/
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-10-28 04:20:21  来源:igfitidea点击:

Replace double backslashes with a single backslash in javascript

javascriptajaxreplacebackslash

提问by Guido Visser

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.

我有一个向服务器执行 AJAX 请求的脚本,服务器C:\backup\在预览中返回。然而,回应是"C:\\backup\\"。没什么大不了的,因为我只是想用单斜线代替双斜线。我一直在堆栈上四处寻找,但我只能找到如何用双反斜杠替换单反斜杠,但我需要反过来。

Can someone help me on this matter?

有人可以帮我解决这个问题吗?

回答by KooiInc

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

这应该这样做: "C:\\backup\\".replace(/\\\\/g, '\\')

In the regular expression, a single \must be escaped to \\, and in the replacement \also.

在正则表达式中,单个\必须转义为\\,并且在替换中\也必须转义。

回答by xxbinxx

Best is to use regex to replace all occurrences:

最好是使用正则表达式来替换所有出现的:

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

this returns: C:\backup\

这将返回: C:\backup\

OR

或者

use split()

使用 split()

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

both produces your desired result

两者都会产生您想要的结果

C:\backup\

C:\备份\

console.log("using \"C:\backup\\".replace(/\/\//g, \"/\")")
console.log("C:\backup\".replace(/\/\//g, "/"));

console.log("Using \"C:\backup\\".split()");
console.log("C:\backup\".split());