繁体   English   中英

如何从 javascript 中的字符串中转义反斜杠

[英]How to escape backslashes from a string in javascript

我的输入是 json 包含 windows 文件路径。 我想在 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);

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

通过将它们加倍来逃避反斜杠。

 // 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 获取链接,则根本不必担心这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM