简体   繁体   English

模板文字中的换行符和字符串文字中的'\\'之间有什么区别?

[英]What's the difference between line breaks in template literals and '\' in string literals?

I was reading about template literals in the ES2015 spec which allows you to create (among other things) line breaks like so: 我正在阅读ES2015规范中的模板文字,它使您可以(如下)创建换行符:

var brokenStr = `This is
    a broken
    string.`; //This is a broken string

We can also break a string literal with the backslash \\ character. 我们还可以使用反斜杠\\字符来分隔字符串文字。

var anotherBrokenStr = 'This is \
    also a broken \
    string.'; //This is also a broken string.

Is there a performance difference between the two? 两者之间是否有性能差异? Which is considered best practice? 哪个被认为是最佳做法?

I have searched SO. 我已经搜索过了。

Update: 更新:

When I output as follows, I get a single line. 当我输出如下时,我得到一行。

document.getElementById('logger').innerHTML = brokenStr;

When I use document.write() I get this in Chrome inspector: 当我使用document.write()我在Chrome检查器中得到了这个:

 This is also a broken string. 

Which colapses the whitespace to a single space in the browser/ 在浏览器/中将空格折叠为单个空格

Update: Update: 更新:更新:

It appears that the template literal includes a \\n character. 看起来模板文字包含\\n字符。 Then, is there any difference between the first example and this, or is it just syntax sugar? 然后,第一个示例与这个示例之间是否有任何区别,或者仅仅是语法糖?

var anotherBrokenStr = 'This is \\n
    also a broken \\n
    string.'; 

Here's the output of my Node.js REPL showing the difference between the two: 这是我的Node.js REPL的输出,显示了两者之间的区别:

> `hello
... world`
'hello\nworld'
> 'hello\
... world'
'helloworld'

In the first case we get a newline between 'hello' and 'world' . 在第一种情况下,我们在'hello''world'之间换行。 In the second case we don't. 在第二种情况下,我们没有。


Edit: Dear Lord, you're thoroughly confused. 编辑:亲爱的上帝,您完全困惑。

 HTML doesn't respect newlines. It doesn't matter how many newlines you put in between your lines. HTML will still print it as a single line. 

Hope that makes things clear. 希望事情能弄清楚。

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

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