如何从 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 获取链接,则完全不必担心。
我的输入是 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 获取链接,则完全不必担心。