简体   繁体   中英

javascript escape newlines in string

I have to define a variable in a template so my template renderer will replace values in it. I then have to use this variable in some javascript functions I have.

The variable is itself some html and I want to be able to format it so that it looks like HTML and not an unreadable super long one line string...

<script>
var myHTML = "
  <div>
    content
  </div>"
</script>

The only way I can see to get it to work would be to do this (really ugly)

<script>
var myHTML = ""
  +"<div>"
    +"content"
  +"</div>"
</script>

Is there a friendly way to do this?

Any new line characters inserted in the source are part of the template literal. Using normal strings, you would have to use the following syntax in order to get multi-line strings :

 var myHTML = '<div>\\n content\\n</div>'; console.log(myHTML); 

For a more advanced usage case you can implement your solution on top of one of these top 5 JavaScript templating engines :

A commonly used and friendly approach to this is to put the template string in its own <script> element with the type attribute set to text/x-something , as this element will be accessible by javascript, but not shown by the browser.

This allows you to write HTML (as well as template markup) as you normally would, without the need for escaping or special handling of newlines.

A working demo of this approach:

 //get the template string var myHTML = document.getElementById("template1").innerHTML; //check that myHTML contains the template string console.log(myHTML); 
 <script type="text/x-template" id="template1"> <div> content </div> </script> 

  1. You just have to put backward slash "\\" at the end of the each line (except last line) of the string and then press enter to go in newline.
  2. In your case:

     <script> var myHTML = '\\ <div>\\ content\\ </div>\\ '; </script> 

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