我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?

text = <<"HERE"
This
Is
A
Multiline
String
HERE

当前回答

ES6允许您使用反勾号在多行上指定字符串。它被称为模板文字。这样地:

var multilineString = `One line of text
    second line of text
    third line of text
    fourth line of text`;

在NodeJS中使用backtick,Chrome、Firefox、Edge、Safari和Opera都支持它。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

其他回答

2015年更新:现在已经过了六年:大多数人使用模块加载器,主要模块系统都有加载模板的方法。它不是内联的,但最常见的多行字符串类型是模板,无论如何,模板应该被排除在JS之外。

require.js:'需要文本'。

使用require.js“text”插件,在template.html中使用多行模板

var template = require('text!template.html')

NPM/browserify:“brfs”模块

Browserify使用“brfs”模块加载文本文件。这实际上会将模板构建到捆绑的HTML中。

var fs = require("fs");
var template = fs.readFileSync(template.html', 'utf8');

容易的

您可以在纯JavaScript中使用多行字符串。

此方法基于函数的序列化,该序列化被定义为依赖于实现。它在大多数浏览器中都能工作(见下文),但不能保证它在未来仍能工作,所以不要依赖它。

使用以下功能:

function hereDoc(f) {
  return f.toString().
      replace(/^[^\/]+\/\*!?/, '').
      replace(/\*\/[^\/]+$/, '');
}

这里可以有这样的文档:

var tennysonQuote = hereDoc(function() {/*!
  Theirs not to make reply,
  Theirs not to reason why,
  Theirs but to do and die
*/});

该方法已在以下浏览器中成功测试(未提及=未测试):

即4-10歌剧9.50-12(不在9-)Safari 4-6(不在3-中)铬1-45Firefox 17-21(非16-)Rekonq 0.7.0-0.8.0Konqueror 4.7.4不支持

不过,要小心你的缩小镜。它倾向于删除评论。对于YUI压缩程序,以/*开头的注释!(像我用过的那个)将被保留。

我认为真正的解决方案是使用CoffeeScript。

ES6 UPDATE:您可以使用backtick代替创建带有注释的函数,并在注释上运行toString。正则表达式需要更新为仅删除空格。您还可以使用字符串原型方法来执行此操作:

let foo = `
  bar loves cake
  baz loves beer
  beer loves people
`.removeIndentation()

应该有人编写此.removeIndentation字符串方法…;)

ES6的方法是使用模板文字:

const str = `This 

is 

a

multiline text`; 

console.log(str);

此处提供更多参考

这适用于IE、Safari、Chrome和Firefox:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<div class="crazy_idea" thorn_in_my_side='<table  border="0">
                        <tr>
                            <td ><span class="mlayouttablecellsdynamic">PACKAGE price $65.00</span></td>
                        </tr>
                    </table>'></div>
<script type="text/javascript">
    alert($(".crazy_idea").attr("thorn_in_my_side"));
</script>

您可以使用+=连接字符串,似乎没有人回答,这将是可读的,也很整洁。。。像这样的东西

var hello = 'hello' +
            'world' +
            'blah';

也可以写成

var hello = 'hello';
    hello += ' world';
    hello += ' blah';

console.log(hello);