Home >Web Front-end >JS Tutorial >How Do I Create Multiline Strings in JavaScript?

How Do I Create Multiline Strings in JavaScript?

DDD
DDDOriginal
2024-12-24 01:01:11247browse

How Do I Create Multiline Strings in JavaScript?

Assigning Multiline Strings to Variables 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:

ES6 Template Literals

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>
`;

ES5 String Concatenation

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn