Javascript: Replace backslashes with double backslashes

落花浮王杯 提交于 2019-11-27 08:25:23

问题


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

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.

EDIT2:

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

回答1:


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.



来源:https://stackoverflow.com/questions/14624295/javascript-replace-backslashes-with-double-backslashes

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