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

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

当前回答

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 string = 'This is\n' +
'a multiline\n' + 
'string';

更新:

ECMAScript6(ES6)引入了一种新的文本类型,即模板文本。它们有很多特性,变量插值等等,但对于这个问题最重要的是,它们可以是多行的。

模板文本由反引号分隔:

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

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

浏览器支持是可以的,但您可以使用更兼容的转发器。


ES5原始答案:

Javascript没有here文档语法。但是,您可以转义字面换行符,这很接近:

"foo \
bar"

我这样编程:

sys = {
    layout: null,
    makeLayout: function (obCLS) {
        this.layout = $('<div />').addClass('editor').appendTo($(obCLS)).append(

            /* Cargador */
            /* @this.layout.find('> div:nth-of-child(1)'); */
            '<div>' +
            '   <p>Seleccione la imagen que desea procesar.</p>' +
            '   <input type="button" value="Seleccionar" class="btn btn-xlarge btn-success" />' +
            '   <span></span>' +
            '</div>' +

            /* Cargador - Progreso */
            /* @this.layout.find('> div:nth-of-child(2)'); */
            '<div>' +
            '   <div>' +
            '       <div></div>' +
            '       <div>' +
            '           <div></div>' +
            '       </div>' +
            '   </div>' +
            '</div>' +

            /* Editor */
            /* @this.layout.find('> div:nth-of-child(3)');
             * @sidebar = this.layout.find('> div:nth-of-child(3) > div > div > div:nth-of-type(1)');
             * @body    = this.layout.find('> div:nth-of-child(3) > div > div > div:nth-of-type(2) > div'); */
            '<div>' +
            '   <div>' +
            '       <div>' +
            '           <div></div>' +
            '           <div>' +
            '               <div></div>' +
            '           </div>' +
            '       </div>' +
            '   </div>' +
            '</div>'
        );
    }
}

sys.makeLayout('#div');

出于对互联网的热爱,请使用字符串连接,并选择不使用ES6解决方案。ES6并不是全面支持的,很像CSS3,某些浏览器适应CSS3的移动速度很慢。使用简单的JavaScript,您的最终用户将感谢您。

例子:

var str=“这个世界既不是平的,也不是圆的。”+“一旦丢失将被发现”;

您可以使用标记的模板来确保获得所需的输出。

例如:

// Merging multiple whitespaces and trimming the output

const t = (strings) => { return strings.map((s) => s.replace(/\s+/g, ' ')).join("").trim() }
console.log(t`
  This
  Is
  A
  Multiline
  String
`);
// Output: 'This Is A Multiline String'

// Similar but keeping whitespaces:

const tW = (strings) => { return strings.map((s) => s.replace(/\s+/g, '\n')).join("").trim() }
console.log(tW`
  This
  Is
  A
  Multiline
  String
`);
// Output: 'This\nIs\nA\nMultiline\nString'