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

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

当前回答

我很惊讶我没有看到这一点,因为它在我测试过的任何地方都有效,并且对模板非常有用:

<script type="bogus" id="multi">
    My
    multiline
    string
</script>
<script>
    alert($('#multi').html());
</script>

有人知道有HTML但不起作用的环境吗?

其他回答

我喜欢这种语法和含义:

string = 'my long string...\n'
       + 'continue here\n'
       + 'and here.';

(但实际上不能视为多行字符串)

这适用于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>

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

const str = `This 

is 

a

multiline text`; 

console.log(str);

此处提供更多参考

准确的

Ruby produce:“This\nIs\nMultiline\nString\n”-在JS下面生成完全相同的字符串

text=`此是A.多行一串`//测试console.log(JSON.stringify(文本));console.log(文本);

这是对朗尼最佳答案的改进,因为他的答案中的换行符与ruby输出中的位置不完全相同

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');

容易的