我有以下的 Ruby 代码。我想将这段代码转换成 JavaScript。请问在 JavaScript 中等价的代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
我有以下的 Ruby 代码。我想将这段代码转换成 JavaScript。请问在 JavaScript 中等价的代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
使用require.js 'text'插件,在template.html中使用多行模板。
var template = require('text!template.html')
Browserify 使用'brfs'模块来加载文本文件。这将实际将您的模板构建到捆绑的HTML中。
var fs = require("fs");
var template = fs.readFileSync(template.html', 'utf8');
简单。
在JavaScript中创建多行字符串最简单的方法是使用反引号(``)。这允许您创建多行字符串,在其中可以插入变量,格式为${variableName}
。
let name = 'Willem';
let age = 26;
let multilineString = `
my name is: ${name}
my age is: ${age}
`;
console.log(multilineString);
ES6
//es2015
中引入的您可以使用TypeScript(JavaScript超集),它支持多行字符串,可在转换回纯JavaScript后不带开销。
var templates = {
myString: `this is
a multiline
string`
}
alert(templates.myString);
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)
'functionName.toString()'
。interface externTemplates
{
myString:string;
}
declare var templates:externTemplates;
alert(templates.myString)
您可以使用来自纯JavaScript变体的多行字符串对象,将模板放入另一个文件中(您可以将其合并到捆绑包中)。
您可以在以下网址尝试TypeScript:
http://www.typescriptlang.org/Playground
ES6允许您使用反引号来指定跨多行的字符串。它被称为模板文字。像这样:
var multilineString = `One line of text
second line of text
third line of text
fourth line of text`;
使用反引号在NodeJS中有效,并且被Chrome、Firefox、Edge、Safari和Opera支持。
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Template_literals
您可以使用标记模板来确保您获得所需的输出结果。
例如:
// 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'
请注意,当使用反斜杠在每行结尾处延长字符串时,如果在反斜杠后面添加了额外的字符(大多是空格、制表符和错误添加的注释),将导致意外的字符错误。我花了一个小时才找到这个问题。
var string = "line1\ // comment, space or tabs here raise error
line2";
带有变量的多行字符串
var x = 1
string = string + `<label class="container">
<p>${x}</p>
</label>`;
var str = "这个世界既不是平坦的,也不是圆形的。"+
"曾经失落的东西将会被找回";