Replace double backslashes with a single backslash in javascript

我与影子孤独终老i 提交于 2019-12-01 01:19:08

问题


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?


回答1:


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

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




回答2:


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());


来源:https://stackoverflow.com/questions/25304214/replace-double-backslashes-with-a-single-backslash-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!