我在 Ruby 中有以下代码。我想将此代码转换为 JavaScript。 JS 中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
如第一个答案所述,使用 ES6 / Babel,您现在只需使用反引号即可创建多行字符串:
const htmlString = `Say hello to
multi-line
strings!`;
插值变量是流行的新功能,带有反引号分隔的字符串:
const htmlString = `${user.name} liked your post about strings`;
这只是转换为串联:
user.name + ' liked your post about strings'
Google 的 JavaScript 样式指南建议使用字符串串联而不是换行符:
不要这样做:
var myString = 'A rather long string of English text, an error message \ actually that just keeps going and going -- an error \ message to make the Energizer bunny blush (right through \ those Schwarzenegger shades)! Where was I? Oh yes, \ you\'ve got an error and all the extraneous whitespace is \ just gravy. Have a nice day.';
在编译时不能安全地剥离每行开头的空白;斜杠后的空格将导致棘手的错误;尽管大多数脚本引擎都支持此功能,但它不是 ECMAScript 的一部分。
请使用字符串串联:
var myString = 'A rather long string of English text, an error message ' + 'actually that just keeps going and going -- an error ' + 'message to make the Energizer bunny blush (right through ' + 'those Schwarzenegger shades)! Where was I? Oh yes, ' + 'you\'ve got an error and all the extraneous whitespace is ' + 'just gravy. Have a nice day.';
模式text = <<"HERE" This Is A Multiline String HERE
在 js 中不可用(我记得在 Perl 过去的美好时光中经常使用它)。
为了对复杂或较长的多行字符串进行监督,有时会使用数组模式:
var myString =
['<div id="someId">',
'some content<br />',
'<a href="#someRef">someRefTxt</a>',
'</div>'
].join('\n');
或已经显示的匿名模式(转义换行符),这可能是代码中的丑陋块:
var myString =
'<div id="someId"> \
some content<br /> \
<a href="#someRef">someRefTxt</a> \
</div>';
这是另一个奇怪但有效的 “技巧” 1 :
var myString = (function () {/*
<div id="someId">
some content<br />
<a href="#someRef">someRefTxt</a>
</div>
*/}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1];
外部编辑: jsfiddle
let str = `This is a text
with multiple lines.
Escapes are interpreted,
\n is a newline.`;
let str = String.raw`This is a text
with multiple lines.
Escapes are not interpreted,
\n is not a newline.`;
1注意:缩小 / 混淆代码后,这将会丢失
您可以在纯 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
*/});
该方法已在以下浏览器中成功测试(未提及 = 未测试):
但是,请小心您的缩小器。它倾向于删除评论。对于YUI 压缩器 ,以/*!
开头的注释/*!
(例如我使用过的那个)将被保留。
我认为真正的解决方案是使用CoffeeScript 。
ES6 更新:您可以使用反引号代替使用注释创建函数并在注释上运行 toString。正则表达式将需要更新为仅删除空格。您也可以使用字符串原型方法来执行此操作:
let foo = `
bar loves cake
baz loves beer
beer loves people
`.removeIndentation()
那会很酷。有人应该写这个. removeIndentation 字符串方法...;)
你可以这样做...
var string = 'This is\n' +
'a multiline\n' +
'string';
我想出了多行字符串的这种非常笨拙的操纵方法。由于将函数转换为字符串还会返回该函数内部的所有注释,因此您可以使用多行注释 / ** / 将注释用作字符串。您只需要修剪两端就可以了。
var 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(myString)
令我惊讶的是,我没有看到它,因为它在我测试过的所有地方都有效,并且对于例如模板非常有用:
<script type="bogus" id="multi">
My
multiline
string
</script>
<script>
alert($('#multi').html());
</script>
有人知道存在 HTML 但无法使用 HTML 的环境吗?
我通过输出 div 使其隐藏并在需要时通过 jQuery 调用 div id 来解决此问题。
例如
<div id="UniqueID" style="display:none;">
Strings
On
Multiple
Lines
Here
</div>
然后,当我需要获取字符串时,只需使用以下 jQuery:
$('#UniqueID').html();
这将在多行上返回我的文本。如果我打电话
alert($('#UniqueID').html());
我得到:
有多种方法可以实现这一目标
1. 斜线连接
var MultiLine= '1\
2\
3\
4\
5\
6\
7\
8\
9';
2. 定期串联
var MultiLine = '1'
+'2'
+'3'
+'4'
+'5';
3. 数组联接串联
var MultiLine = [
'1',
'2',
'3',
'4',
'5'
].join('');
在性能方面, Slash 串联 (第一个)是最快的。
有关性能的更多详细信息, 请参考 此测试用例
更新:
借助ES2015 ,我们可以利用其模板字符串功能。有了它,我们只需要使用反引号来创建多行字符串
例:
`<h1>{{title}}</h1>
<h2>{{hero.name}} details!</h2>
<div><label>id: </label>{{hero.id}}</div>
<div><label>name: </label>{{hero.name}}</div>
`
使用脚本标签:
head
标签中添加一个包含多行文本的<script>...</script>
块; 按原样获取多行文本...(请注意文本编码:UTF-8,ASCII)
<script>
// pure javascript
var text = document.getElementById("mySoapMessage").innerHTML ;
// using JQuery's document ready for safety
$(document).ready(function() {
var text = $("#mySoapMessage").html();
});
</script>
<script id="mySoapMessage" type="text/plain">
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:typ="...">
<soapenv:Header/>
<soapenv:Body>
<typ:getConvocadosElement>
...
</typ:getConvocadosElement>
</soapenv:Body>
</soapenv:Envelope>
<!-- this comment will be present on your string -->
//uh-oh, javascript comments... SOAP request will fail
</script>