Home >Web Front-end >JS Tutorial >How Do I Create Multiline Strings in JavaScript?
Q: How do I convert this Ruby code with a multiline string into JavaScript?
text = <<HERE This Is A Multiline String HERE
In Ruby, the << operator allows one to define multiline strings. How can this approach be implemented in JavaScript?
A:
Modern JavaScript (ES6 ) provides template literals as a way to declare multiline strings. These literals are enclosed in backticks (`) and can span multiple lines, preserving line breaks.
For instance:
const html = ` <div> <span>Some HTML here</span> </div> `;
Prior to ES6, JavaScript required using string concatenation or escaped new lines to achieve multiline strings. Concatenating strings with allows one to break a string over multiple lines, as seen below:
const text = "This\n" + "Is\n" + "A\n" + "Multiline\n" + "String";
Alternatively, one can escape new line characters with n:
const text = "foo \ bar";
The above is the detailed content of How Do I Create Multiline Strings in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!