简体   繁体   English

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

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

My input is a json containing windows file paths.我的输入是 json 包含 windows 文件路径。 I would like to display the file paths in html.我想在 html 中显示文件路径。 Note that I cannot change the input string.请注意,我无法更改输入字符串。 Does anybody know what operation I can execute on my input string so that the backslashes would be displayed in my html page?有人知道我可以对输入字符串执行什么操作,以便反斜杠显示在我的 html 页面中吗? I have been searching through many questions already, but I don't seem to find a solution for this problem.我已经搜索了很多问题,但我似乎没有找到解决这个问题的方法。

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

When I use this code, no backslashes are displayed.当我使用此代码时,不显示反斜杠。

Escape the backslashes by doubling them.通过将它们加倍来逃避反斜杠。

 // 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>

If you can't change the code, there's no solution.如果您无法更改代码,则没有解决方案。 Escape sequences are replaced when parsing string literals, there's no way to recover the original source.解析字符串文字时会替换转义序列,无法恢复原始来源。

Escape sequences are only processed in string literals in source code.转义序列仅在源代码中的字符串文字中处理。 If you're getting the links from user input or an API, you don't have to worry about this at all.如果您从用户输入或 API 获取链接,则根本不必担心这一点。

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

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