¿Cómo puedo escapar de una sola cita?


¿Cómo puedo escapar de un ' (comillas simples) en JavaScript?

Aquí es donde estoy tratando de usarlo:

<input type='text' id='abc' value='hel'lo'>

El resultado para el código anterior es "hel" rellenado en el cuadro de texto. Traté de reemplazar ' con\', pero esto lo que estoy recibiendo.

<input type='text' id='abc' value='hel\'lo'>

El resultado para el código anterior es "hel\" rellenado en el cuadro de texto.

¿Cómo puedo escapar con éxito de las comillas simples?

 142
Author: Peter Mortensen, 2010-03-11

6 answers

Puedes usar entidades HTML:

  • &#39; para '
  • &#34; para "
  • ...

Para obtener más información, puede echar un vistazo a Referencias de entidades de caracteres en HTML.

 275
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
2017-11-10 20:13:29

Puedes usar &apos; (que es dudoso en IE) o &#39; (que debería funcionar en todas partes). Para obtener una lista completa, consulte W3C HTML5 Named Character References o la tabla de entidades HTML en WebPlatform.org .

 49
Author: Benjamin Manns,
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-28 03:05:46

Como estás en el contexto de HTML, necesitas usar HTML para representar ese carácter. Y para HTML necesita usar una referencia de caracteres numéricos &#39; (&#x27; hexadecimal):

<input type='text' id='abc' value='hel&#39;lo'>
 7
Author: Gumbo,
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-03-11 20:56:19

Representarlo como entidad de texto (ASCII 39):

<input type='text' id='abc' value='hel&#39;lo'>
 5
Author: AndiDog,
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-03-11 20:56:24

Probablemente la forma más fácil:

<input type='text' id='abc' value="hel'lo">
 2
Author: road242,
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-03-11 20:54:59

Puedes intentar usar: &#145;

 -2
Author: thelost,
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-17 23:38:48