简体   繁体   中英

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:

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:

 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. 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:

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

In the first case we get a newline between 'hello' and '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.

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