在JavaScript中创build多行string

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

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

更新:

ECMAScript 6(ES6)引入了一种新的文字,即模板文字 。 它们有很多特征,其中包括可变插值,但最重要的是对于这个问题,它们可以是多行的。

模板文字由反引号分隔:

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

(注意:我不主张在string中使用HTML)

浏览器支持是可以的 ,但是你可以使用转译器来更加兼容。


原来的ES5答案:

Javascript没有here-document语法。 你可以转义字面换行符,但是,接近:

 "foo \ bar" 

更新:

使用ES6 / Babel,您现在可以简单地使用反引号创build多行string:

 var htmlString = `Say hello to multi-line strings!`; 

原来的ES5答案:

Google的JavaScript风格指南build议使用string连接而不是转义换行符:

不要这样做:

 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的一部分。

改用string连接:

 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时代使用它很多)。

为了保持对复杂或长的多行string的监督,我有时使用一个数组模式:

 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

[ 2015年增加 ]
ES6支持使用模板string在多行上跨越string :

 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中可以有多行string。

此方法基于函数的序列化,这些函数被定义为与实现有关 。 它在大多数浏览器中都能正常工作(见下文),但是不能保证它在将来仍能正常工作,所以不要依赖它。

使用以下function:

 function hereDoc(f) { return f.toString(). replace(/^[^\/]+\/\*!?/, ''). replace(/\*\/[^\/]+$/, ''); } 

你可以在这里find这样的文件:

 var tennysonQuote = hereDoc(function() {/*! Theirs not to make reply, Theirs not to reason why, Theirs but to do and die */}); 

该方法已成功地在以下浏览器(未提及=未经testing)进行testing:

  • IE 4 – 10
  • 歌剧9.50 – 12(不在9-)
  • Safari 4 – 6(不在3-)
  • Chrome 1 – 45
  • 火狐17 – 21( 不在16- )
  • Rekonq 0.7.0 – 0.8.0
  • Konqueror 4.7.4不支持

虽然,小心你的小型机。 它倾向于删除评论。 对于YUI压缩机 ,以/*!开头的注释 (就像我使用的那个)将被保留。

我认为一个真正的解决scheme是使用CoffeeScript 。

你可以这样做…

 var string = 'This is\n' + 'a multiline\n' + 'string'; 

我想出了一个多行string的这个非常简单的方法。 由于将函数转换为string也会返回函数内部的任何注释,因此可以使用多行注释/ ** /将注释用作string。 你只需要削减两端,你有你的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) 

我很惊讶,我没有看到这一点,因为它在我testing过的任何地方都能正常工作,对于例如模板非常有用:

 <script type="bogus" id="multi"> My multiline string </script> <script> alert($('#multi').html()); </script> 

有没有人知道有HTML的环境,但不起作用?

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

例如

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

然后当我需要获取string时,我只使用下面的jQuery:

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

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

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

我得到:

在这里输入图像描述

使用脚本标签:

  • 将包含多行文本的<script>...</script>块添加head标记中;
  • 让你的多行文本…(注意文本编码: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> 

我喜欢这个语法和indendation:

 string = 'my long string...\n' + 'continue here\n' + 'and here.'; 

(但实际上不能被视为多行string)

有多种方法来实现这一点

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串联 (第一个)是最快的。

请参考 这个testing案例了解更多关于性能的细节

更新:

借助ES2015 ,我们可以利用其“模板string”function。 有了它,我们只需要使用back-ticks来创build多行string

例:

  `<h1>{{title}}</h1> <h2>{{hero.name}} details!</h2> <div><label>id: </label>{{hero.id}}</div> <div><label>name: </label>{{hero.name}}</div> ` 

有这个库使它变得美丽:

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> */}); 

Downvoters :此代码仅供参考。

这已经在Mac上的Fx 19和Chrome 24上进行了testing

DEMO

 var new_comment; /*<<<EOF <li class="photobooth-comment"> <span class="username"> <a href="#">You</a> </span> <span class="comment-text"> $text </span> <span class="comment-time"> 2d </span> </li> EOF*/ // note the script tag here is hardcoded as the FIRST tag new_comment=document.currentScript.innerHTML.split("EOF")[1]; alert(new_comment.replace('$text','Here goes some text')); 

总结一下,我已经在用户javascript编程(Opera 11.01)中尝试了2种方法:

  • 这一个没有工作: 在JavaScript中创build多行string
  • 这工作相当好,我也想出了如何使它看起来不错在Notepad ++源代码视图: 在JavaScript中创build多行string

所以我build议Opera用户JS用户的工作方式。 不像作者所说的那样:

它不适用于Firefox或Opera; 只在IE浏览器,铬和Safari浏览器。

它在Opera 11中工作。至less在用户JS脚本。 太糟糕了,我不能评论个人的答案或upvote答案,我会立即做。 如果可能的话,有更高特权的人请为我做。

2015年更新 :六年后的今天:大多数人使用模块加载器,主模块系统都有加载模板的方法。 它不是内联的,但最常见的多行string是模板,而且模板通常应该保持在JS之外

require.js:“需要文本”。

使用require.js的“文本”插件 ,在template.html中使用多行模板

 var template = require('text!template.html') 

NPM / browserify:“brfs”模块

Browserify 使用“brfs”模块来加载文本文件。 这实际上会将您的模板构build到捆绑的HTML中。

 var fs = require("fs"); var template = fs.readFileSync(template.html', 'utf8'); 

简单。

如果你愿意使用逃脱的换行符,可以很好地使用它们。 它看起来像一个带有页面边框的文档

在这里输入图像描述

您可以使用TypeScript (JavaScript SuperSet),它支持多行string,并且无需额外开销就可以转换回纯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变体中的多行string对象,您可以在其中将模板放入另一个文件(可以在该包中合并)。

你可以试试TypeScript
http://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> 

我的扩展到https://stackoverflow.com/a/15558082/80404 。 它期望以一种forms发表评论/*! any multiline comment */ /*! any multiline comment */符号! 用于防止通过缩小(至less对于YUI压缩机)

 Function.prototype.extractComment = function() { var startComment = "/*!"; var endComment = "*/"; var str = this.toString(); var start = str.indexOf(startComment); var end = str.lastIndexOf(endComment); return str.slice(start + startComment.length, -(str.length - end)); }; 

例:

 var tmpl = function() { /*! <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> </ul> </div> */}.extractComment(); 

在JavaScript中的等效是:

 var text = ` This Is A Multiline String `; 

这是规范 。 请参阅本页底部的浏览器支持。 这里也是一些例子 。

ES6允许您使用反引号在多行上指定一个string。 它被称为模板文字。 喜欢这个:

 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/en-US/docs/Web/JavaScript/Reference/Template_literals

我的版本的基于数组的连接stringconcat:

 var c = []; //c stands for content c.push("<div id='thisDiv' style='left:10px'></div>"); c.push("<div onclick='showDo(\'something\');'></div>"); $(body).append(c.join('\n')); 

这对我来说效果很好,特别是我经常用这种方式将值插入到html中。 但是它有很多限制。 缩进会很好。 不用处理嵌套的引号会非常好,而且它的笨重让我困扰。

是否将.push()添加到数组占用很多时间? 看到这个相关的答案:

( 有什么原因JavaScript开发人员不使用Array.push()? )

看着这些(相反的)testing运行后,它看起来像.push()适用于string数组,这将不会增长超过100个项目 – 我会避免它赞成索引添加更大的数组。

你可以使用+=连接你的string,好像没有人回答,这将是可读的,也整洁…像这样的东西

 var hello = 'hello' + 'world' + 'blah'; 

也可以写成

 var hello = 'hello'; hello += ' world'; hello += ' blah'; console.log(hello); 

另外请注意,在每行末尾使用前向反斜杠将多个string进行多行扩展时,在正向反斜杠之后的任何多余字符(大部分是空格,制表符和注释)会导致意想不到的字符错误,我花了一个小时才find出

 var string = "line1\ // comment, space or tabs here raise error line2"; 

你必须使用连接运算符'+'。

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <p id="demo"></p> <script> var str = "This " + "\n<br>is " + "\n<br>multiline " + "\n<br>string."; document.getElementById("demo").innerHTML = str; </script> </body> </html> 

通过使用\n您的源代码将看起来像 –

这个 
 结果是
 结果多
 结果string。

通过使用<br>您的浏览器输出将看起来像 –

这个
是
多
串。

请为互联网使用string连接的爱,select不使用ES6解决scheme。 ES6并不是全部支持的,就像CSS3一样,某些浏览器也很难适应CSS3的运动。 使用普通的“JavaScript”,你的最终用户会感谢你。

例:

var str = "This world is neither flat nor round. "+ "Once was lost will be found";

我认为这个解决方法应该可以在IE,Chrome,Firefox,Safari,Opera –

使用jQuery

 <xmp id="unique_id" style="display:none;"> Some plain text Both type of quotes : " ' " And ' " ' JS Code : alert("Hello World"); HTML Code : <div class="some_class"></div> </xmp> <script> alert($('#unique_id').html()); </script> 

使用纯Javascript:

 <xmp id="unique_id" style="display:none;"> Some plain text Both type of quotes : " ' " And ' " ' JS Code : alert("Hello World"); HTML Code : <div class="some_class"></div> </xmp> <script> alert(document.getElementById('unique_id').innerHTML); </script> 

干杯!!

刚刚尝试匿名回答,发现这里有一个小窍门,如果反斜杠后有一个空格\
所以下面的解决scheme是行不通的 –

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

希望它有帮助!

i found a more elegant solution, maybe a little non-topic related because it uses PHP, but im sure it will be useful and cuteness* for some of yours…

this javascript code should stay inside script tags

 var html=<?php echo json_encode(" <div class=container> <div class=area1> xxx </div> <div class=area2> ".$someVar." </div> </div> "); ?> 

in your output html you will see something like

 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"; 

and et voilà! , it gives you code readability in your file.

pD: this sample uses json_encode() PHP function, but certainly there are function equivalents for ASP, Ruby and JSP langs.

pD: however, this solution have his limitations too, one of them is you cannot use javascript variables inside the encapsulated code.

If you happen to be running in Node only, you could use the fs module to read in the multi-line string from a file:

 var diagram; var fs = require('fs'); fs.readFile( __dirname + '/diagram.txt', function (err, data) { if (err) { throw err; } diagram = data.toString(); });