Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

javascript - 在JavaScript中创建多行字符串(Creating multiline strings in JavaScript)

I have the following code in Ruby.

(我在Ruby中有以下代码。)

I want to convert this code into JavaScript.

(我想将此代码转换为JavaScript。)

what's the equivalent code in JS?

(JS中的等效代码是什么?)

text = <<"HERE"
This
Is
A
Multiline
String
HERE
  ask by Newy translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Update:(更新:)

ECMAScript 6 (ES6) introduces a new type of literal, namely template literals .

(ECMAScript 6(ES6)引入了一种新型的文字,即模板文字 。)

They have many features, variable interpolation among others, but most importantly for this question, they can be multiline.

(它们具有许多功能,其中包括变量插值,但对于这个问题最重要的是,它们可以是多行的。)

A template literal is delimited by backticks :

(模板文字由反引号分隔:)

var html = `
  <div>
    <span>Some HTML here</span>
  </div>
`;

(Note: I'm not advocating to use HTML in strings)

((注意:我不主张在字符串中使用HTML))

Browser support is OK , but you can use transpilers to be more compatible.

(浏览器支持还可以 ,但是您可以使用编译器来更好地兼容。)


Original ES5 answer:(ES5原始答案:)

Javascript doesn't have a here-document syntax.

(Javascript没有here-document语法。)

You can escape the literal newline, however, which comes close:

(但是,您可以转义文字换行符,该换行符很接近:)

"foo 
bar"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...