简体   繁体   English

javascript转义字符串中的换行符

[英]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. 然后我必须在我的一些javascript函数中使用此变量。

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... 变量本身就是一些html,我希望能够对它进行格式化,使其看起来像HTML,而不是一个不可读的超长单行字符串......

<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 : 对于更高级的用例,您可以在这些前5个JavaScript模板引擎之一上实现您的解决方案:

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. 一种常用且友好的方法是将模板字符串放在其自己的<script>元素中,并将type属性设置为text/x-something ,因为此元素可以通过javascript访问,但不会被浏览器显示。

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. 这允许您像往常一样编写HTML(以及模板标记),而无需转义或特殊处理换行符。

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. 你只需要在字符串的每一行(除了最后一行)的末尾加上反斜杠“\\”,然后按Enter键进入换行符。
  2. In your case: 在你的情况下:

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

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

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