我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
我在Ruby中有以下代码。我想把这段代码转换成JavaScript。JS中的等效代码是什么?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
当前回答
我想我发现了另一种方法,可以在没有任何侵入性语法的情况下,在每一行中内联执行。使用Javascript将函数转换为字符串并使用/**/语法创建多行注释,然后删除“function(){/*\n”和“\n*/}”。
var multiline = function(string) { return string.toString().replace(/(^[^\n]*\n)|(\n\*\/\})/g, ""); };
console.log(multiline(function() {/*
Hello world!
I'm a multiline string!
Tada!
*/}));
我能看到的唯一缺陷是语法高亮显示。
编辑:如果我再向下滚动一点,我会看到这个答案完全一样:https://stackoverflow.com/a/5571069/916553
其他回答
有这样一个图书馆,它很漂亮:
https://github.com/sindresorhus/multiline
之前
var str = '' +
'<!doctype html>' +
'<html>' +
' <body>' +
' <h1>❤ unicorns</h1>' +
' </body>' +
'</html>' +
'';
之后
var str = multiline(function(){/*
<!doctype html>
<html>
<body>
<h1>❤ unicorns</h1>
</body>
</html>
*/});
我通过输出一个div,使其隐藏,并在需要时通过jQuery调用div id来解决这个问题。
e.g.
<div id="UniqueID" style="display:none;">
Strings
On
Multiple
Lines
Here
</div>
然后,当我需要获取字符串时,我只需使用以下jQuery:
$('#UniqueID').html();
它会在多行上返回我的文本。如果我打电话
alert($('#UniqueID').html());
我得到:
我找到了一个更优雅的解决方案,可能有点与主题无关,因为它使用了PHP,但我相信它对你的一些人来说会很有用和可爱。。。
这个javascript代码应该留在脚本标记中
var html=<?php echo json_encode("
<div class=container>
<div class=area1>
xxx
</div>
<div class=area2>
".$someVar."
</div>
</div>
"); ?>
在输出html中,您将看到类似
var html="\r\n\r\n\t\t\t<div class=container>\r\n\t\t\t\t<div class=area1>\r\n\t\t\t\t\txxx\r\n\t\t\t\t<\/div>\r\n\t\t\t\t<div class=area2>\r\n\t\t\t\t\t44\r\n\t\t\t\t<\/div>\r\n\t\t\t<\/div>\r\n\r\n\t\t";
瞧!,它为您的文件提供了代码可读性。
pD:此示例使用json_encode()PHP函数,但当然也有ASP、Ruby和JSP语言的等效函数。
pD:然而,这个解决方案也有他的局限性,其中之一就是不能在封装的代码中使用javascript变量。
这适用于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>
刚刚尝试了Anonymous的答案,发现这里有一个小技巧,如果反斜杠后面有空格,它就不起作用了因此,以下解决方案不起作用-
var x = { test:'<?xml version="1.0"?>\ <-- One space here
<?mso-application progid="Excel.Sheet"?>'
};
但当空间被移除时,它会起作用-
var x = { test:'<?xml version="1.0"?>\<-- No space here now
<?mso-application progid="Excel.Sheet"?>'
};
alert(x.test);
希望它有帮助!!