简体   繁体   中英

How to put a newline in a template string

I have a template string where in I'm using an array like this:

var templateString = `array is ${arr.join(",\n")}`;

The newline doesn't show up. How can I put a newline in this case?

It works perfectly if you're trying to display it in the console:

 var arr = [1, 2, 3]; var templateString = `array is ${arr.join(",\\n")}`; console.log(templateString); 

If you want to display it in HTML, use a HTML linebreak ( <br> ):

 var arr = [1, 2, 3]; var templateString = `array is ${arr.join(",<br />")}`; document.write(templateString); 

You can do this:

var arr = ["Saab", "Volvo", "BMW", "dd"];
var templateString = `array is ${arr.join(",<br>")}`;
//This is getting displayed in HTML hence used break line so that it renders.
document.getElementById("demo").innerHTML = templateString;

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