如何将多行字符串文字分配给变量?
如何将带有多行字符串的 Ruby 代码转换为 JavaScript?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
How do I convert this Ruby code with a multiline string into JavaScript?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
ES6 允许您使用反引号在多行上指定一个字符串。它称为模板文字。像这样:
在 NodeJS 中可以使用反引号,并且 Chrome、Firefox、Edge、Safari 和 Opera 都支持它。
https://developer.mozilla.org/en-US/docs /Web/JavaScript/Reference/Template_literals
ES6 allows you to use a backtick to specify a string on multiple lines. It's called a Template Literal. Like this:
Using the backtick works in NodeJS, and it's supported by Chrome, Firefox, Edge, Safari, and Opera.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
您可以使用标记模板来确保获得所需的输出。
例如:
You can use tagged templates to make sure you get the desired output.
For example:
另请注意,当在每行末尾使用正向反斜杠将字符串扩展到多行时,正向反斜杠后的任何额外字符(主要是空格、制表符和错误添加的注释)都会导致意外的字符错误,我花了一个小时才找到出去
Also do note that, when extending string over multiple lines using forward backslash at end of each line, any extra characters (mostly spaces, tabs and comments added by mistake) after forward backslash will cause unexpected character error, which i took an hour to find out
出于对互联网的热爱,请使用字符串连接并选择不使用 ES6 解决方案。 ES6 并未得到全面支持,就像 CSS3 一样,并且某些浏览器适应 CSS3 运动的速度很慢。使用简单的 JavaScript,您的最终用户会感谢您。
示例:
var str =“这个世界既不是平的也不是圆的。”+
“一旦失去,就会被找到”;
Please for the love of the internet use string concatenation and opt not to use ES6 solutions for this. ES6 is NOT supported all across the board, much like CSS3 and certain browsers being slow to adapt to the CSS3 movement. Use plain ol' JavaScript, your end users will thank you.
Example:
var str = "This world is neither flat nor round. "+
"Once was lost will be found";
带变量的多行字符串
Multiline string with variables
更新:
ECMAScript 6 (ES6) 引入了一种新的文字类型,即 模板文字。它们有很多功能,变量插值等,但对于这个问题最重要的是,它们可以是多行的。
模板文字由反引号分隔:(
注意:我不提倡在字符串中使用 HTML)
浏览器支持还可以,但您可以使用转译器来提高兼容性。
ES5 原始答案:
Javascript 没有此处文档语法。但是,您可以转义文字换行符,它很接近:
Update:
ECMAScript 6 (ES6) introduces a new type of literal, namely template literals. 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:
(Note: I'm not advocating to use HTML in strings)
Browser support is OK, but you can use transpilers to be more compatible.
Original ES5 answer:
Javascript doesn't have a here-document syntax. You can escape the literal newline, however, which comes close:
ES6 更新:
正如第一个答案提到的,使用 ES6/Babel,您现在只需使用反引号即可创建多行字符串:
插值变量是一项流行的新功能,带有反引号分隔字符串:
这只是转换为串联:
ES5 原始答案:
ES6 Update:
As the first answer mentions, with ES6/Babel, you can now create multi-line strings simply by using backticks:
Interpolating variables is a popular new feature that comes with back-tick delimited strings:
This just transpiles down to concatenation:
Original ES5 answer:
模式
text = <<"HERE" This Is A Multiline String HERE
在 js 中不可用(我记得在我美好的 Perl 岁月里经常使用它)。为了对复杂或长的多行字符串进行监督,我有时会使用数组模式:
或已经显示的匿名模式(转义换行符),这可能是代码中的一个丑陋的块:
这是另一个奇怪但有效的“技巧”1:
外部编辑:jsfiddle
ES20xx 支持使用 模板字符串:
1 注意:在缩小/混淆代码后,这将丢失
the pattern
text = <<"HERE" This Is A Multiline String HERE
is not available in js (I remember using it much in my good old Perl days).To keep oversight with complex or long multiline strings I sometimes use an array pattern:
or the pattern anonymous already showed (escape newline), which can be an ugly block in your code:
Here's another weird but working 'trick'1:
external edit: jsfiddle
ES20xx supports spanning strings over multiple lines using template strings:
1 Note: this will be lost after minifying/obfuscating your code
您可以在纯 JavaScript 中使用多行字符串。
此方法基于函数的序列化,该函数定义为依赖于实现 。它确实可以在大多数浏览器中工作(见下文),但不能保证它将来仍然可以工作,所以不要依赖它。
使用以下功能:
您可以在此处拥有这样的文档:
该方法已在以下浏览器中成功测试(未提及 = 未测试):
不过,请小心您的压缩器。它往往会删除评论。对于 YUI 压缩器,以
/*!
开头的注释(例如我使用的那个)将被保留。我认为真正的解决方案是使用 CoffeeScript。
ES6 更新:您可以使用反引号,而不是创建带有注释的函数并在注释上运行 toString。正则表达式需要更新为仅删除空格。您还可以有一个字符串原型方法来执行此操作:
有人应该编写这个 .removeIndentation 字符串方法...;)
You can have multiline strings in pure JavaScript.
This method is based on the serialization of functions, which is defined to be implementation-dependent. It does work in the most browsers (see below), but there's no guarantee that it will still work in the future, so do not rely on it.
Using the following function:
You can have here-documents like this:
The method has successfully been tested in the following browsers (not mentioned = not tested):
Be careful with your minifier, though. It tends to remove comments. For the YUI compressor, a comment starting with
/*!
(like the one I used) will be preserved.I think a real solution would be to use CoffeeScript.
ES6 UPDATE: You could use backtick instead of creating a function with a comment and running toString on the comment. The regex would need to be updated to only strip spaces. You could also have a string prototype method for doing this:
Someone should write this .removeIndentation string method... ;)
你可以这样做...
You can do this...
我想出了这个非常吉米操纵的多线绳索方法。由于将函数转换为字符串还会返回函数内的任何注释,因此您可以使用多行注释 /**/ 将注释用作字符串。你只需要把末端剪掉就可以了。
I came up with this very jimmy rigged method of a multi lined string. Since converting a function into a string also returns any comments inside the function you can use the comments as your string using a multilined comment /**/. You just have to trim off the ends and you have your string.
我很惊讶我没有看到这个,因为它在我测试过的任何地方都有效,并且对于例如模板非常有用:
有人知道有 HTML 但它不起作用的环境吗?
I'm surprised I didn't see this, because it works everywhere I've tested it and is very useful for e.g. templates:
Does anybody know of an environment where there is HTML but it doesn't work?
我通过输出一个 div,将其隐藏,并在需要时通过 jQuery 调用 div id 来解决这个问题。
例如
,当我需要获取字符串时,我只需使用以下 jQuery:
它会在多行上返回我的文本。如果我打电话,
我会得到:
I solved this by outputting a div, making it hidden, and calling the div id by jQuery when I needed it.
e.g.
Then when I need to get the string, I just use the following jQuery:
Which returns my text on multiple lines. If I call
I get:
有多种方法可以实现这一目标
1。斜杠连接
2.常规连接
3.数组连接连接
从性能角度来看,斜线连接(第一个)是最快的。
请参阅此测试用例,了解有关性能的更多详细信息
更新:
ES2015,我们可以利用它的模板字符串功能。有了它,我们只需要使用反引号来创建多行字符串
示例:
There are multiple ways to achieve this
1. Slash concatenation
2. regular concatenation
3. Array Join concatenation
Performance wise, Slash concatenation (first one) is the fastest.
Refer this test case for more details regarding the performance
Update:
With the ES2015, we can take advantage of its Template strings feature. With it, we just need to use back-ticks for creating multi line strings
Example:
使用脚本标签:
块添加到
head
标签中;按原样获取多行文本...(注意文本编码:UTF-8、ASCII)
<前><代码><脚本>;
// 纯 JavaScript
var text = document.getElementById("mySoapMessage").innerHTML ;
// 为了安全起见,使用 JQuery 的文档
$(文档).ready(函数() {
var text = $("#mySoapMessage").html();
});
<脚本 id="mySoapMessage" type="text/plain">
<类型:getConvocadosElement>
...
//呃-哦,JavaScript 注释... SOAP 请求将失败
Using script tags:
<script>...</script>
block containing your multiline text intohead
tag;get your multiline text as is... (watch out for text encoding: UTF-8, ASCII)
在 JavaScript 中打印多行字符串的一种简单方法是使用由反引号 (``) 表示的模板文字(模板字符串)。您还可以在模板字符串中使用变量(`
name is ${value}
`)您还可以
A simple way to print multiline strings in JavaScript is by using template literals(template strings) denoted by backticks (` `). you can also use variables inside a template string-like (`
name is ${value}
`)You can also
我喜欢这种语法和缩进:(
但实际上不能被视为多行字符串)
I like this syntax and indendation:
(but actually can't be considered as multiline string)
反对者:此代码仅供参考。
此功能已在 Mac 上的 Fx 19 和 Chrome 24 中进行了测试
DEMO
Downvoters: This code is supplied for information only.
This has been tested in Fx 19 and Chrome 24 on Mac
DEMO
有一个让它变得美丽的库:
https://github.com/sindresorhus/multiline
之前
之后
There's this library that makes it beautiful:
https://github.com/sindresorhus/multiline
Before
After
在这里找到了很多过度设计的答案。
我认为两个最好的答案是:
1:
最终记录:
2:
正确记录它,但如果 str 嵌套在函数/对象等内部,则在脚本文件中很难看...:
我使用正则表达式记录的非常简单的答案str 正确:
请注意,这不是完美的解决方案,但如果您确定新行 (\n) 之后至少会出现一个空格(+ 表示至少出现一次),则它可以工作。它还适用于 *(零个或多个)。
您可以更明确地使用 {n,} 表示至少出现 n 次。
Found a lot of over engineered answers here.
The two best answers in my opinion were:
1:
which eventually logs:
2:
That logs it correctly but it's ugly in the script file if str is nested inside functions / objects etc...:
My really simple answer with regex which logs the str correctly:
Please note that it is not the perfect solution but it works if you are sure that after the new line (\n) at least one space will come (+ means at least one occurrence). It also will work with * (zero or more).
You can be more explicit and use {n,} which means at least n occurrences.
javascript 中的等效内容是:
这是规范。请参阅此页面底部的浏览器支持。这里还有一些示例。
The equivalent in javascript is:
Here's the specification. See browser support at the bottom of this page. Here are some examples too.
精确的
Ruby 产生:
“This\nIs\nA\nMultiline\nString\n”
-下面的 JS 产生完全相同的字符串这是对Lonnie最佳答案的改进,因为他的答案中的换行符与ruby输出中的位置不完全相同
Exact
Ruby produce:
"This\nIs\nA\nMultiline\nString\n"
- below JS produce exact same stringThis is improvement to Lonnie Best answer because new-line characters in his answer are not exactly the same positions as in ruby output
这适用于 IE、Safari、Chrome 和 Firefox:
This works in IE, Safari, Chrome and Firefox:
总而言之,我尝试了用户 javascript 编程(Opera 11.01)中列出的两种方法:
所以我推荐 Opera 用户 JS 用户的工作方法。与作者所说的不同:
它确实可以在 Opera 11 中工作。至少在用户 JS 脚本中是这样。太糟糕了,我无法对个别答案发表评论或对答案进行投票,我会立即这样做。如果可能的话,请有更高权限的人帮我做。
to sum up, I have tried 2 approaches listed here in user javascript programming (Opera 11.01):
So I recommend the working approach for Opera user JS users. Unlike what the author was saying:
It DOES work in Opera 11. At least in user JS scripts. Too bad I can't comment on individual answers or upvote the answer, I'd do it immediately. If possible, someone with higher privileges please do it for me.
我对 https://stackoverflow.com/a/15558082/80404 的扩展。
它需要以
/*! 形式的注释。任何多行注释 */
其中符号 !用于防止缩小删除(至少对于 YUI 压缩器)示例:
My extension to https://stackoverflow.com/a/15558082/80404.
It expects comment in a form
/*! any multiline comment */
where symbol ! is used to prevent removing by minification (at least for YUI compressor)Example:
2015年更新:现在已经六年了:大多数人都使用模块加载器,并且主要模块系统都有加载模板的方法。它不是内联的,但最常见的多行字符串类型是模板,并且模板通常应该远离 JS。
require.js:“需要文本”。
使用 require.js 'text' 插件,并在 template.html
NPM/browserify:“brfs”模块
Browserify 使用“brfs”模块加载文本文件。这实际上会将您的模板构建到捆绑的 HTML 中。
简单的。
Updated for 2015: it's six years later now: most people use a module loader, and the main module systems each have ways of loading templates. It's not inline, but the most common type of multiline string are templates, and templates should generally be kept out of JS anyway.
require.js: 'require text'.
Using require.js 'text' plugin, with a multiline template in template.html
NPM/browserify: the 'brfs' module
Browserify uses a 'brfs' module to load text files. This will actually build your template into your bundled HTML.
Easy.
如果您愿意使用转义换行符,它们可以很好地使用。 它看起来像一个带有页面边框的文档。
If you're willing to use the escaped newlines, they can be used nicely. It looks like a document with a page border.
在 JavaScript 中创建多行字符串的最简单方法是使用反引号 (``)。这允许您创建多行字符串,您可以在其中插入带有
${variableName}
的变量。例子:
兼容性:
ES6
//es2015
中引入的在此处检查 Mozilla 文档中的确切兼容性
Easiest way to make multiline strings in Javascrips is with the use of backticks ( `` ). This allows you to create multiline strings in which you can insert variables with
${variableName}
.Example:
compatibility :
ES6
//es2015
Check exact compatibility in Mozilla docs here
ES6 的方法是使用模板文字:
更多参考 这里
The ES6 way of doing it would be by using template literals:
More reference here
您可以使用 TypeScript (JavaScript SuperSet),它支持多行字符串,并且无需开销即可转换回纯 JavaScript :
如果您想使用纯 JavaScript 完成相同的任务:
请注意,iPad/Safari 不支持
'functionName.toString()'
如果您有大量遗留代码,您还可以使用TypeScript 中的纯 JavaScript 变体(用于清理目的):
您可以使用纯 JavaScript 变体中的多行字符串对象,将模板放入另一个文件中(您可以将其合并到包中)。
您可以在
处尝试 TypeScript
http://www.typescriptlang.org/Playground
You can use TypeScript (JavaScript SuperSet), it supports multiline strings, and transpiles back down to pure JavaScript without overhead:
If you'd want to accomplish the same with plain JavaScript:
Note that the iPad/Safari does not support
'functionName.toString()'
If you have a lot of legacy code, you can also use the plain JavaScript variant in TypeScript (for cleanup purposes):
and you can use the multiline-string object from the plain JavaScript variant, where you put the templates into another file (which you can merge in the bundle).
You can try TypeScript at
http://www.typescriptlang.org/Playground