.trim () en JavaScript no funciona en IE


Traté de aplicar .trim() a una cadena en uno de mis programas JavaScript. Está funcionando bien bajo Mozilla, pero se muestra un error cuando lo pruebo en IE8. ¿Alguien sabe lo que está pasando aquí? ¿Puedo hacer que funcione en IE?

Código:

var ID = document.getElementByID('rep_id').value.trim();

Pantalla de error:

Message: Object doesn't support this property or method
Line: 604
Char: 2
Code: 0
URI: http://test.localhost/test.js
Author: Shog9, 2010-02-22

14 answers

Agregue el siguiente código para agregar la funcionalidad trim a la cadena.

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}
 765
Author: Ben Rowe,
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-07-26 06:58:43

Parece que esa función no está implementada en IE. Si estás usando jQuery, puedes usar $.trim() en su lugar ( http://api.jquery.com/jQuery.trim/).

 201
Author: jrummell,
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-02-22 00:43:32

[2]} jQuery:

$.trim( $("#mycomment").val() );

Alguien usa $("#mycomment").val().trim(); pero esto no funcionará en IE.

 56
Author: Dan,
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-04-24 17:45:30

Desafortunadamente no hay soporte para JavaScript entre navegadores para trim().

Si no está utilizando jQuery (que tiene un .método trim ()) puede usar los siguientes métodos para agregar soporte de trim a cadenas:

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
    return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");
}
 32
Author: Iain Collins,
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-06-24 09:00:25

Https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/String/Trim

Esta es una adición bastante reciente a javascript, y no es compatible con IE.

 12
Author: Erik,
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-02-22 00:40:38

Tuve un problema similar al intentar recortar un valor de una entrada y luego preguntar si era igual a nada:

if ($(this).val().trim() == "")

Sin embargo, esto arrojó una llave inglesa en las obras para IE6 - 8. Bastante molesto había tratado de var hasta así:

   var originalValue = $(this).val();

Sin embargo, usando el método trim de jQuery, funciona perfectamente para mí en todos los navegadores..

var originalValueTrimmed = $.trim($(this).val());              
            if (originalValueTrimmed  == "") { ... }
 8
Author: kaichanvong,
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-23 23:09:27

He escrito algún código para implementar la funcionalidad trim.

LTRIM (recortar a la izquierda):

function ltrim(s)
{
    var l=0;
    while(l < s.length && s[l] == ' ')
    {   l++; }
    return s.substring(l, s.length);
} 

RTRIM (recortar a la derecha):

function rtrim(s)
{
    var r=s.length -1;
    while(r > 0 && s[r] == ' ')
    {   r-=1;   }
    return s.substring(0, r+1);
 }

TRIM (recortar ambos lados):

function trim(s)
{
    return rtrim(ltrim(s));
}

O

También está disponible la expresión regular que podemos usar.

function trimStr(str) {
  return str.replace(/^\s+|\s+$/g, '');
}

Explicación útil

 5
Author: shiv.mymail,
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:18

Podemos obtener el código oficial de Internet! Refiérase a esto:

Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim

Ejecutar el siguiente código antes que cualquier otro código creará trim() si no está disponible de forma nativa.

if (!String.prototype.trim) {
  (function() {
    // Make sure we trim BOM and NBSP
    var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
    String.prototype.trim = function() {
      return this.replace(rtrim, '');
    };
  })();
}

Para más: Acabo de encontrar que hay un proyecto js para soportar ECMAScript 5: https://github.com/es-shims/es5-shim al leer el código fuente, podemos obtener más conocimiento sobre trim.

defineProperties(StringPrototype, {
 // http://blog.stevenlevithan.com/archives/faster-trim-javascript
 // http://perfectionkills.com/whitespace-deviations/
  trim: function trim() {
    if (typeof this === 'undefined' || this === null) {
      throw new TypeError("can't convert " + this + ' to object');
    }
    return String(this).replace(trimBeginRegexp, '').replace(trimEndRegexp, '');
  }
}, hasTrimWhitespaceBug);
 4
Author: Will V King,
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-03-13 07:10:39

No creo que haya un método nativo trim() en el estándar JavaScript. Tal vez Mozilla suministra uno, pero si quieres uno en IE, tendrás que escribirlo tú mismo. Hay algunas versiones en esta página.

 3
Author: JW.,
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-04-24 17:45:58

Tuve el mismo problema en IE9 Sin embargo, cuando declaré la versión html compatible con la siguiente etiqueta en la primera línea antes de la

<!DOCTYPE html>
<HTML>
<HEAD>...
.
.

El problema se resolvió.

 3
Author: Mark,
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-14 03:51:19
var res = function(str){
    var ob; var oe;
    for(var i = 0; i < str.length; i++){
        if(str.charAt(i) != " " && ob == undefined){ob = i;}
        if(str.charAt(i) != " "){oe = i;}
    }
    return str.substring(ob,oe+1);
}
 0
Author: Dhaval dave,
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-03-20 18:04:21

Acaba de descubrir que IE deja de soportar trim(), probablemente después de una actualización reciente de Windows. Si usas dojo, puedes usar dojo.string.trim(), funciona multiplataforma.

 0
Author: David Zhao,
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-04-24 17:46:18

Este problema puede ser causado por IE usando el modo de compatibilidad en sitios de intranet. Hay dos formas de resolver esto, puede actualizar IE para no usar el modo de compatibilidad en su máquina local (en IE11: Herramientas-> Configuración de la vista de compatibilidad -> Desmarque Mostrar sitios de intranet en la vista de compatibilidad)

Mejor aún, puedes actualizar las meta etiquetas en tu página web. Añadir:

...
<head>
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
</head>
...

¿Qué significa esto? Le está diciendo a IE que use el último modo de compatibilidad. Más información disponible en MSDN: Especificar los modos de documento heredados

 0
Author: FuzzyJulz,
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-12-17 01:14:55

Esto se debe a un error tipográfico getElementBy ID. Cambiar a getElementById

 0
Author: Aswathy,
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-03-23 14:21:26