Javascript:用双反斜杠替换反斜杠
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14624295/
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
Javascript: Replace backslashes with double backslashes
提问by vm370
I'm currently having the problem mentioned in the title and I'm somehow not finding a way to properly replace backsashes with double backslashes, so that I can properly give the string to a webservice as parameters. Let me show you what I tried. Some of these do actually work for some other people, but not for me... I'm currently testing this with FF18.0.1
我目前遇到了标题中提到的问题,但不知何故我找不到用双反斜杠正确替换反斜杠的方法,以便我可以正确地将字符串作为参数提供给 web 服务。让我告诉你我的尝试。其中一些确实适用于其他一些人,但不适用于我......我目前正在使用 FF18.0.1 进行测试
WSParameters.replace(/\/g, "\\\\");
WSParameters.replace("\", "\\\\");
WSParameters.replace(/\/g, "\\");
WSParameters.replace(/\/g, "\\");
WSParameters.replace(/\/g, "\");
WSParameters.replace("\", "\\");
Thanks a lot in advance
非常感谢提前
EDIT: I should mention that it's somehow parsed into JSON and with firebug I see the backslash in the source string, but not in the JSON view. Maybe there is another way? But somehow it's already failing at the replacement of the backslashes.
编辑:我应该提到它以某种方式被解析为 JSON,并且使用 firebug 我在源字符串中看到反斜杠,但在 JSON 视图中没有。也许还有另一种方式?但不知何故,它已经在替换反斜杠方面失败了。
EDIT2:
编辑2:
if (noAction == false) {
$.ajax({
type: "POST",
url: "WebService.asmx/" + webMethod,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: pAsync,
data: WSParameters,
success: function callFunction(result) { processPOSTResults(result, pType, pNot);},
error: function (xhr, ajaxOptions, thrownError) {
alert('Error while communicating with WebAdmin web service. - ' + xhr.status + " " + thrownError);
}
});
}
回答by Bergi
WSParameters.replace(/\\/g, "\\\\");
should do it, and in FF18 as well. Notice that if you use JSON.stringify
, this is done automatically. Also watch out that many console outputs (Firebug etc) do surround string contents with quotes, but do not escape them.
WSParameters.replace(/\\/g, "\\\\");
应该这样做,在FF18中也是如此。请注意,如果您使用JSON.stringify
,这是自动完成的。还要注意许多控制台输出(Firebug 等)确实用引号将字符串内容括起来,但不要对它们进行转义。