【问题标题】:How to escape backslashes from a string in javascript如何从javascript中的字符串中转义反斜杠
【发布时间】:2020-07-23 14:13:08
【问题描述】:

我的输入是一个包含 windows 文件路径的 json。我想在 html 中显示文件路径。请注意,我无法更改输入字符串。有人知道我可以对输入字符串执行什么操作,以便在我的 html 页面中显示反斜杠吗?我已经搜索了很多问题,但我似乎没有找到解决这个问题的方法。

// The json would be something like this.
data = [ 
  {"name": "Something", "link": "C:\something\something"},
  {"name": "Something Else", "link": "C:\something\something_else"}
  ];

// Loop over the json and add the elements to the html afterwards
var list = '';
$.each(data, function () {                    
    list += `
    <p> ${this.name} </p>
    <input class="form-control" type="text" value="${this.link}">
    `;
  });

$(".some-container").html(list);

当我使用此代码时,不显示反斜杠。

【问题讨论】:

    标签: javascript jquery string escaping backslash


    【解决方案1】:

    通过将反斜杠加倍来转义它们。

    // The json would be something like this.
    data = [ 
      {"name": "Something", "link": "C:\\something\\something"},
      {"name": "Something Else", "link": "C:\\something\\something_else"}
      ];
    
    // Loop over the json and add the elements to the html afterwards
    var list = '';
    $.each(data, function () {                    
        list += `
        <p> ${this.name} </p>
        <input class="form-control" type="text" value="${this.link}">
        `;
      });
    
    $(".some-container").html(list);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="some-container"></div>

    如果您无法更改代码,则没有解决方案。解析字符串文字时转义序列被替换,无法恢复原始来源。

    转义序列仅在源代码中以字符串文字处理。如果您从用户输入或 API 获取链接,则完全不必担心这一点。

    【讨论】:

    • 在我的帖子中我这样说:“请注意,我无法更改输入字符串。”我知道这是一个可能的解决方案,但我无法手动将 json 中的所有反斜杠更改为双反斜杠。
    • 那你就不走运了。解析代码时会删除反斜杠,无法恢复它们。你需要修复你的代码。
    • 谢谢。假设用户在网站的输入字段中输入了一个字符串。并且所述字符串包含反斜杠。那么这个反斜杠也会被删除吗?
    • 不,这仅适用于源代码中的字符串文字。输入数据中不处理转义序列。
    猜你喜欢
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    • 2012-08-02
    • 2021-12-16
    • 2016-06-03
    • 2019-07-31
    相关资源
    最近更新 更多