JavaScript string newline character?


Es \n la secuencia universal de caracteres de nueva línea en Javascript para todas las plataformas? Si no, ¿cómo determino el carácter para el entorno actual?

No estoy preguntando por el elemento HTML newline (<BR/>). Estoy preguntando por la secuencia de caracteres de nueva línea utilizada dentro de las cadenas de JavaScript.

Author: askewchan, 2009-07-21

16 answers

Acabo de probar algunos navegadores usando este tonto poco de JavaScript:

function log_newline(msg, test_value) {
  if (!test_value) { 
    test_value = document.getElementById('test').value;
  }
  console.log(msg + ': ' + (test_value.match(/\r/) ? 'CR' : '')
              + ' ' + (test_value.match(/\n/) ? 'LF' : ''));
}

log_newline('HTML source');
log_newline('JS string', "foo\nbar");
log_newline('JS template literal', `bar
baz`);
<textarea id="test" name="test">

</textarea>

IE8 y Opera 9 en Windows usan \r\n. Todos los otros navegadores que probé (Safari 4 y Firefox 3.5 en Windows, y Firefox 3.0 en Linux) usan \n. Todos pueden manejar \n muy bien al establecer el valor, aunque IE y Opera convertirán eso de nuevo a \r\n de nuevo internamente. Hay un artículo de SitePoint con más detalles llamado Javascript .

Tenga en cuenta también que esto es independiente de los finales de línea reales en el propio archivo HTML (tanto \n como \r\n dan los mismos resultados).

Al enviar un formulario, todos los navegadores canonizan las nuevas líneas a %0D%0A en la codificación de URL. Para ver eso, cargue, por ejemplo, data:text/html,<form><textarea name="foo">foo%0abar</textarea><input type="submit"></form> y presione el botón enviar. (Algunos navegadores bloquean la carga de la página enviada, pero puede ver los valores de formulario codificados con URL en la consola.)

No creo que realmente necesites hacer mucho de cualquier determinando, sin embargo. Si solo desea dividir el texto en nuevas líneas, podría hacer algo como esto:

lines = foo.value.split(/\r\n|\r|\n/g);
 332
Author: mercator,
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-11-03 12:05:43

Sí, es universal.

Aunque '\n' son los caracteres universales de nueva línea, debe tener en cuenta que, dependiendo de su entrada, los caracteres de nueva línea pueden ir precedidos por caracteres de retorno de carro ('\r').

 72
Author: Sinan Taifour,
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
2009-07-20 20:09:33

No uses \n, solo prueba esto:

    var string = "this\
    is a multi\
    line\
    string";

Sólo tienes que introducir una barra hacia atrás y seguir en truckin'! Funciona como un encanto.

 47
Author: Qasim,
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-04-10 07:51:55

Podría ser más fácil manejar todos los casos del nuevo carácter de línea en lugar de verificar qué caso luego aplicarlo. Por ejemplo, si necesita reemplazar la nueva línea, haga lo siguiente:

htmlstring = stringContainingNewLines.replace(/(\r\n|\n|\r)/gm, "<br>");
 46
Author: Quincy,
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-21 20:32:53

Sí use \n, a menos que esté generando código html, en el que desee usar <br />

 22
Author: Finer Recliner,
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-05-12 21:26:57

Función de enlace de correo electrónico uso "%0D % 0A "

function sendMail() {   
var bodydata="Before "+ "%0D%0A";
    bodydata+="After"

var MailMSG = "mailto:[email protected]" 
         + "[email protected]" 
         + "&subject=subject" 
         + "&body=" + bodydata; 
window.location.href = MailMSG; 
} 

[HTML]

<a href="#" onClick="sendMail()">Contact Us</a>
 12
Author: ISCI,
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-11-28 04:54:32

Obtener un separador de líneas para el navegador actual:

function getLineSeparator() {
  var textarea = document.createElement("textarea");
  textarea.value = "\n"; 
  return textarea.value;
}
 6
Author: Vitalii Fedorenko,
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-02-01 00:34:49

Una nota - cuando se utiliza ExtendScript JavaScript (el lenguaje de scripting de Adobe utilizado en aplicaciones como Photoshop CS3+), el carácter a utilizar es "\r". "\n " se interpretará como un carácter de fuente, y muchas fuentes tendrán un carácter de bloque en su lugar.

Por ejemplo (para seleccionar una capa llamada 'Note' y agregar feeds de línea después de todos los períodos):

var layerText = app.activeDocument.artLayers.getByName('Note').textItem.contents;
layerText = layerText.replace(/\. /g,".\r");
 3
Author: JayCrossler,
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-04-07 23:44:34

En la respuesta a Nilay anterior (no puedo comentar, no hay suficiente reputación):

¿Alguien conoce este tipo de código para la tecla tab? he probado "%0D % 09 " pero no funciona. - Nilay Sep 26 ' 15 at 13:57

Pestaña es un solo carácter, por lo que si intenta%09 debería estar bien. Un ejemplo para ver los códigos de caracteres individuales:

var output = "";
var s="aaa\tbbb\tccc";
for (var i = 0; i < s.length; i++) {
  output += "i=" + i + " charAt=" + s.charAt(i) + " charCodeAt=" + s.charCodeAt(i) + "\n";
}

console.log(output);
 2
Author: Pik Master,
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-11-03 11:21:36

Tuve el problema de expresar una nueva línea con \n o \r\n.
Mágicamente el carácter \r que se usa para el retorno de carro funcionó para mí como una nueva línea.
Así que en algunos casos, es útil considerar \r también.

 1
Author: Oralet,
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-02-02 14:45:14

Puede usar ` comillas " (que están debajo del botón Esc) con ES6. Así que puedes escribir algo como esto:

var text = `fjskdfjslfjsl
skfjslfkjsldfjslfjs
jfsfkjslfsljs`;
 1
Author: Bogdan Surai,
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-26 12:46:13

Creo que lo es when cuando estás trabajando con cadenas JS.

Si está generando HTML, sin embargo, tendrá que usar etiquetas <br /> (no \n, ya que ya no está tratando con JS)

 0
Author: Pascal MARTIN,
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
2009-07-20 20:12:28
printAccountSummary: function()
        {return "Welcome!" + "\n" + "Your balance is currently $1000 and your interest rate is 1%."}
};
console.log(savingsAccount.printAccountSummary()); // method

Impresiones:

Welcome!
Your balance is currently $1000 and your interest rate is 1%.
 0
Author: Barbs G,
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-05-17 04:15:27

Puedes usar los valores hexadecimales ascii, algo como esto (esto funcionó para mí):

 var string = "this %0d%0a is a multiline %0d%0a string";

El resultado será:

this 
is a multiline 
string
 0
Author: Wekerle Tibor,
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-07-24 05:34:06

El \n está bien para todos los casos que he encontrado. Si está trabajando con web, use \n y no se preocupe por ello (a menos que haya tenido problemas relacionados con la nueva línea).

 -3
Author: zzandy,
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
2009-09-11 14:53:14

Puede utilizar <br/> y el document.write/, document.writeln uno.

 -10
Author: omari Powell,
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-04-16 23:53:23