Reputation: 345
My input is a json containing windows file paths. I would like to display the file paths in 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? 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.
Upvotes: 0
Views: 370
Reputation: 780974
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.
Upvotes: 2