Creación de cadenas multilínea en JavaScript


Tengo el siguiente código en Ruby. Quiero convertir este código en JavaScript. cuál es el código equivalente en JS?

text = <<"HERE"
This
Is
A
Multiline
String
HERE
Author: Potherca, 2009-04-30

30 answers

Actualización:

ECMAScript 6 (ES6) introduce un nuevo tipo de literal, a saber literales de plantilla. Tienen muchas características, interpolación variable entre otras, pero lo más importante para esta pregunta, pueden ser multilínea.

Un literal de plantilla está delimitado por backsticks :

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

(Nota: No estoy abogando por el uso de HTML en cadenas)

El soporte del navegador está bien, pero puede usar transpilers para ser más compatible.


Respuesta original ES5:

Javascript no tiene una sintaxis here-document. Sin embargo, puede escapar de la nueva línea literal, que se acerca:

"foo \
bar"
 2398
Author: Anonymous,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-14 16:47:51

Actualización ES6:

Como se menciona en la primera respuesta, con ES6 / Babel, ahora puede crear cadenas multilíneas simplemente usando backsticks:

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

La interpolación de variables es una nueva característica popular que viene con cadenas delimitadas por marcas de retroceso:

const htmlString = `${user.name} liked your post about strings`;

Esto solo transpila a la concatenación:

user.name + ' liked your post about strings'

Respuesta original ES5:

La guía de estilo JavaScript de Google recomienda usar concatenación de cadenas en lugar de escapar de nuevas líneas:

No hagas esto:

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.';

El espacio en blanco al principio de cada línea no se puede eliminar de forma segura en tiempo de compilación; el espacio en blanco después de la barra diagonal dará lugar a errores difíciles; y aunque la mayoría de los motores de script soportan esto, no es parte de ECMAScript.

Usa concatenación de cadenas en su lugar:

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.';
 1137
Author: Devin G Rhode,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-02 19:26:20

El patrón text = <<"HERE" This Is A Multiline String HERE no está disponible en js (recuerdo usarlo mucho en mis viejos días de Perl).

Para mantener la supervisión con cadenas multilíneas complejas o largas, a veces uso un patrón de matriz:

var myString = 
   ['<div id="someId">',
    'some content<br />',
    '<a href="#someRef">someRefTxt</a>',
    '</div>'
   ].join('\n');

O el patrón anónimo ya mostrado (escape newline), que puede ser un bloque feo en tu código:

    var myString = 
       '<div id="someId"> \
some content<br /> \
<a href="#someRef">someRefTxt</a> \
</div>';

Aquí hay otro truco extraño pero que funciona'1:

var myString = (function () {/*
   <div id="someId">
     some content<br />
     <a href="#someRef">someRefTxt</a>
    </div>        
*/}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1];

externo editar: jsfiddle

ES20xx admite cadenas que abarcan varias líneas utilizando cadenas de plantilla :

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 Nota: esto se perderá después de minificar/ofuscar su código

 637
Author: KooiInc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-24 06:58:06

Usted puede tener cadenas multilínea en JavaScript puro.

Este método se basa en la serialización de funciones, que se define como dependiente de la implementación. Funciona en la mayoría de los navegadores (ver más abajo), pero no hay garantía de que seguirá funcionando en el futuro, así que no confíe en él.

Usando la siguiente función:

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

Puede tener aquí-documentos como este:

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

El método ha sido probado con éxito en el los siguientes navegadores (no mencionado = no probado):

  • IE 4-10
  • Opera 9.50 - 12 (no en 9 -)
  • Safari 4 - 6 (no en 3 -)
  • Cromo 1 - 45
  • Firefox 17 - 21 ( no en 16-)
  • Rekonq 0.7.0-0.8.0
  • No es compatible con Konqueror 4.7.4

Tenga cuidado con su minifier, sin embargo. Tiende a eliminar comentarios. Para el YUI compressor , un comentario que comience con /*! (como el que usé) ser preservado.

Creo que una solución realsería usar CoffeeScript.

 329
Author: Jordão,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-09 19:00:36

Puedes hacer esto...

var string = 'This is\n' +
'a multiline\n' + 
'string';
 186
Author: alex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-19 04:14:47

Se me ocurrió este método muy Jimmy amañado de una cadena de múltiples líneas. Dado que convertir una función en una cadena también devuelve cualquier comentario dentro de la función, puede usar los comentarios como su cadena utilizando un comentario multilineado /**/. Solo tienes que recortar los extremos y tienes tu cuerda.

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)
 107
Author: Luke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-21 21:05:15

Me sorprende no haber visto esto, porque funciona en todas partes que lo he probado y es muy útil para, por ejemplo, plantillas:

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

¿Alguien sabe de un entorno donde hay HTML pero no funciona?

 82
Author: Peter V. Mørch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-03 19:51:51

Resolví esto al generar un div, ocultarlo y llamar al id de div por jQuery cuando lo necesitaba.

Por ejemplo

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

Luego, cuando necesito obtener la cadena, solo uso la siguiente jQuery:

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

Que devuelve mi texto en varias líneas. Si llamo

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

Obtengo:

introduzca la descripción de la imagen aquí

 46
Author: Tom Beech,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-16 14:20:52

Usando etiquetas de script:

  • agregue un bloque <script>...</script> que contenga su texto multilínea en la etiqueta head;
  • Obtenga su texto multilínea tal cual... (cuidado con la codificación de texto: 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>
    
 27
Author: jpfreire,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-03 13:58:41

Hay múltiples maneras de lograr esto

1. Concatenación de barra oblicua

  var MultiLine=  '1\
    2\
    3\
    4\
    5\
    6\
    7\
    8\
    9';

2. concatenación regular

var MultiLine = '1'
+'2'
+'3'
+'4'
+'5';

3. Concatenación de combinación de matriz

var MultiLine = [
'1',
'2',
'3',
'4',
'5'
].join('');

En cuanto al rendimiento, La concatenación de barra diagonal (la primera) es la más rápida.

Referir este caso de prueba para más detalles sobre el rendimiento

Actualización:

Con el ES2015 , podemos aprovechar su Plantilla función de cadenas. Con él, solo necesitamos usar back-ticks para crear cadenas de varias líneas

Ejemplo:

 `<h1>{{title}}</h1>
  <h2>{{hero.name}} details!</h2>
  <div><label>id: </label>{{hero.id}}</div>
  <div><label>name: </label>{{hero.name}}</div>
  `
 26
Author: Vignesh Subramanian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-08 08:33:50

Me gusta esta sintaxis y la indendación:

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

(pero en realidad no se puede considerar como cadena multilínea)

 24
Author: semente,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-13 20:09:10

Hay una biblioteca que lo hace hermoso:

Https://github.com/sindresorhus/multiline

Antes

var str = '' +
'<!doctype html>' +
'<html>' +
'   <body>' +
'       <h1>❤ unicorns</h1>' +
'   </body>' +
'</html>' +
'';

Después de

var str = multiline(function(){/*
<!doctype html>
<html>
    <body>
        <h1>❤ unicorns</h1>
    </body>
</html>
*/});
 17
Author: mightyiam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-25 11:34:57

Downvoters : Este código se proporciona únicamente a título informativo.

Esto ha sido probado en Fx 19 y Chrome 24 en Mac

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'));
 13
Author: mplungjan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-17 15:44:57

Para resumir, he intentado 2 enfoques enumerados aquí en programación javascript de usuario (Opera 11.01):

Así que recomiendo el enfoque de trabajo para los usuarios de Opera JS. A diferencia de lo que el autor estaba diciendo:

It no funciona en Firefox u opera; solo en IE, chrome y safari.

Funciona en Opera 11. Al menos en scripts JS de usuario. Lástima que no puedo comentar las respuestas individuales o votar a favor de la respuesta, lo haría de inmediato. Si es posible, alguien con privilegios superiores por favor hágalo por mí.

 10
Author: Tyler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:47:36

Actualizado para 2015: ya han pasado seis años: la mayoría de la gente usa un cargador de módulos, y cada uno de los sistemas de módulos principales tiene formas de cargar plantillas. No está en línea, pero el tipo más común de cadena multilínea son las plantillas, y las plantillas generalmente deben mantenerse fuera de JS de todos modos.

Requerir.js: 'requerir texto'.

Usando require.plugin js' text ' , con una plantilla multilínea en la plantilla .html

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

NPM / browserify: los 'brfs' módulo

Browserify utiliza un módulo 'brfs' para cargar archivos de texto. Esto realmente construirá su plantilla en su HTML incluido.

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

Fácil.

 8
Author: mikemaccana,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-31 17:48:21

Si estás dispuesto a usar las nuevas líneas escapadas, se pueden usar muy bien. parece un documento con un borde de página.

introduzca la descripción de la imagen aquí

 8
Author: seo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-30 14:14:03

Esto funciona en IE, Safari, Chrome y 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>
 7
Author: stillatmycomputer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-23 16:46:29

Mi extensión a https://stackoverflow.com/a/15558082/80404. Se espera comentario en una forma /*! any multiline comment */ donde símbolo ! se utiliza para evitar la eliminación por minificación (al menos para el compresor 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));
};

Ejemplo:

var tmpl = function() { /*!
 <div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
    </ul>
 </div>
*/}.extractComment();
 7
Author: pocheptsov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:37

Puede usar TypeScript (Superconjunto JavaScript), admite cadenas multilínea y transpila de nuevo a JavaScript puro sin sobrecarga:

var templates = {
    myString: `this is
a multiline
string` 
}

alert(templates.myString);

Si desea lograr lo mismo con JavaScript simple:

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)

Tenga en cuenta que el iPad/Safari no es compatible con 'functionName.toString()'

Si tiene mucho código heredado, también puede usar la variante de JavaScript simple en TypeScript (para fines de limpieza):

interface externTemplates
{
    myString:string;
}

declare var templates:externTemplates;

alert(templates.myString)

Y puede usar el objeto multiline-string desde la variante simple de JavaScript, donde pones las plantillas en otro archivo (que puedes combinar en el paquete).

Puede probar TypeScript en
http://www.typescriptlang.org/Playground

 7
Author: Stefan Steiger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-07 13:12:07

El equivalente en javascript es:

var text = `
This
Is
A
Multiline
String
`;

Aquí está la especificación . Consulte el soporte del navegador en la parte inferior de esta página . Aquí hay algunos ejemplos también.

 7
Author: Lonnie Best,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-04 14:06:18

ES6 le permite usar una comilla para especificar una cadena en varias líneas. Se llama Plantilla Literal. Así:

var multilineString = `One line of text
    second line of text
    third line of text
    fourth line of text`;

El uso del backtick funciona en NodeJS, y es compatible con Chrome, Firefox, Edge, Safari y Opera.

Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

 5
Author: earl3s,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-28 18:43:26

Mi versión de la combinación basada en matrices para cadena concat:

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

Esto ha funcionado bien para mí, especialmente porque a menudo inserto valores en el html construido de esta manera. Pero tiene muchas limitaciones. La muesca estaría bien. No tener que lidiar con comillas anidadas sería realmente agradable, y solo el volumen de la misma me molesta.

Es el .push() para agregar a la matriz que toma mucho tiempo? Ver esta respuesta relacionada:

(¿Hay alguna razón por la que los desarrolladores de JavaScript no uses Array.push ()?)

Después de mirar estas (opuestas) ejecuciones de prueba, parece .push () está bien para matrices de cadenas que probablemente no crecerán más de 100 elementos - lo evitaré a favor de adiciones indexadas para matrices más grandes.

 3
Author: KTys,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:59

Puede usar += para concatenar su cadena, parece que nadie respondió eso, lo que será legible y también limpio... algo como esto

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

También se Puede escribir como

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

console.log(hello);
 3
Author: Mr. Alien,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-18 13:18:54

También tenga en cuenta que, al extender la cadena sobre varias líneas usando barra invertida hacia adelante al final de cada línea, cualquier carácter adicional (en su mayoría espacios, pestañas y comentarios añadidos por error) después de barra invertida hacia adelante causará un error de carácter inesperado, que me tomé una hora para averiguar

var string = "line1\  // comment, space or tabs here raise error
line2";
 3
Author: Prakash GPz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-13 19:25:31

Por favor, por amor a Internet, use la concatenación de cadenas y opte por no usar soluciones ES6 para esto. ES6 NO es compatible en todos los ámbitos, al igual que CSS3 y ciertos navegadores son lentos para adaptarse al movimiento CSS3. Use JavaScript simple, sus usuarios finales se lo agradecerán.

Ejemplo:

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

 3
Author: Pragmatiq,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-11 23:28:47

La forma más fácil de hacer cadenas multilíneas en Javascrips es con el uso de backsticks ( ` ). Esto le permite crear cadenas multilíneas en las que puede insertar variables con ${variableName}.

Ejemplo:

let name = 'Willem'; 
let age = 26;

let multilineString = `
my name is: ${name}

my age is: ${age}
`;

console.log(multilineString);

Compatibilidad:

  • Se introdujo en ES6//es2015
  • Ahora es compatible de forma nativa con todos los principales proveedores de navegadores (excepto Internet explorer)

Compruebe la compatibilidad exacta en los documentos de Mozilla aquí

 3
Author: Willem van der Veen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-01 21:27:45

Tienes que usar el operador de concatenación '+'.

<!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>

Al usar \n su código fuente se verá como -

This 
 <br>is
 <br>multiline
 <br>string.

Al usar <br> la salida de su navegador se verá como -

This
is
multiline
string.
 2
Author: Sonevol,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-13 22:57:20

Creo que esta solución debería funcionar en IE, Chrome, Firefox, Safari, Opera -

Usando 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>

Usando Javascript puro :

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

Salud!!

 1
Author: Aditya Hajare,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-28 12:20:46

Acabo de probar la respuesta anónima y encontré que hay un pequeño truco aquí, no funciona si hay un espacio después de la barra invertida \
Así que la siguiente solución no funciona -

var x = { test:'<?xml version="1.0"?>\ <-- One space here
            <?mso-application progid="Excel.Sheet"?>' 
};

Pero cuando se quita el espacio funciona -

var x = { test:'<?xml version="1.0"?>\<-- No space here now
          <?mso-application progid="Excel.Sheet"?>' 
};

alert(x.test);​

Espero que ayude !!

 0
Author: Anmol Saraf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-23 13:10:00

Si se ejecuta solo en el nodo, puede usar el módulo fs para leer la cadena multilínea de un archivo:

var diagram;
var fs = require('fs');
fs.readFile( __dirname + '/diagram.txt', function (err, data) {
  if (err) {
    throw err; 
  }
  diagram = data.toString();
});
 0
Author: Charles Brandt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-09 00:02:29