简体   繁体   中英

How to escape backslashes from a string in javascript

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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