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

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

当前回答

我通过输出一个div,使其隐藏,并在需要时通过jQuery调用div id来解决这个问题。

e.g.

<div id="UniqueID" style="display:none;">
     Strings
     On
     Multiple
     Lines
     Here
</div>

然后,当我需要获取字符串时,我只需使用以下jQuery:

$('#UniqueID').html();

它会在多行上返回我的文本。如果我打电话

alert($('#UniqueID').html());

我得到:

其他回答

您可以使用TypeScript(JavaScript SuperSet),它支持多行字符串,并将文件向下转换为纯JavaScript而无需开销:

var templates = {
    myString: `this is
a multiline
string` 
}

alert(templates.myString);

如果您想用普通JavaScript实现同样的功能:

var templates = 
{
 myString: function(){/*
    This is some
    awesome multi-lined
    string using a comment 
    inside a function 
    returned as a string.
    Enjoy the jimmy rigged code.
*/}.toString().slice(14,-3)

}
alert(templates.myString)

请注意,iPad/Safari不支持“functionName.toString()”

如果您有很多遗留代码,也可以在TypeScript中使用纯JavaScript变量(用于清理):

interface externTemplates
{
    myString:string;
}

declare var templates:externTemplates;

alert(templates.myString)

您可以使用普通JavaScript变体中的多行字符串对象,将模板放入另一个文件中(可以合并到捆绑包中)。

您可以在以下位置尝试TypeScripthttp://www.typescriptlang.org/Playground

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

此处提供更多参考

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

容易的

带变量的多行字符串

var x = 1
string = string + `<label class="container">
                       <p>${x}</p>
                   </label>`;