ChatGPT解决这个技术问题 Extra ChatGPT

.trim() in JavaScript not working in IE

I tried to apply .trim() to a string in one of my JavaScript programs. It's working fine under Mozilla, but an error displays when I try it in IE8. Does anyone know what is going on here? Is there anyway I can make it work in IE?

code:

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

error display:

Message: Object doesn't support this property or method
Line: 604
Char: 2
Code: 0
URI: http://test.localhost/test.js
I can't see what is stored on your computer. Could you upload test.js to a storage website? Also, I need to see the actual trim() function to see what is wrong. Thanks!
@ItzWarty "whatever ".trim() try that on IE8.
I Googled for IE8 compatibility for trim(), and wouldn't believe my eyes when I figured out it was unsupported. Thanks for clearing that out. I was going to ask the same as you asked.

B
Ben Rowe

Add the following code to add trim functionality to the string.

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

Good answer. Note that replace(/^\s\s*/, '').replace(/\s\s*$/, '') should be about 3 times faster than replace(/^\s+|\s+$/, '') in Firefox 2, according to one benchmark: blog.stevenlevithan.com/archives/faster-trim-javascript
Note also that replace(/^\s+|\s+$/, '') only removes either leading or trailing spaces, which is not the behavior expected from a trim function. If you want to remove both leading and trailing spaces you need to use replace(/^\s+|\s+$/g, '').
Seems a bit silly to me. Doesn't every js framework provide a utility trim() function? If this is the only issue you have, then fine, but there's plenty of ways that IE is "different" that will make a library worth-while in the short-run.
@Stephen Yes you're correct, but the question isn't about frameworks. it's about javascript & trim.
This is a nice solution if you don't use jQuery. But if not, $.trim() seems to be a much better solution, as it keeps your script a little bit simpler.
d
double-beep

It looks like that function isn't implemented in IE. If you're using jQuery, you could use $.trim() instead (although is has been deprecated as of jQuery 3.5).


Now, I love jQuery, but importing it just for .trim() seems overkill
I agree. That's why I said "if you're using jQuery ..." =)
@Erik is this going to be the only IE issue Jin is going to run into? There's not a lot of useful javascript I can write without having to use a library's browser sanitisation functions.
Please note that $.trim() is diff from $(<element>.val().trim() - more info here: stackoverflow.com/questions/4315570/…
S
Sampson

jQuery:

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

Someone uses $("#mycomment").val().trim(); but this will not work on IE.


Thank-you for a perfect answer which has saved us many headaches here on this rotten shaky old Browser-Bridge :)
A great example of why jQuery.
Is that method cross browser, Sir?
@toha, being cross browser is one of the key things about jQuery
Correct Sir. I guess. Thanks
I
Iain Collins

Unfortunately there is not cross browser JavaScript support for trim().

If you aren't using jQuery (which has a .trim() method) you can use the following methods to add trim support to strings:

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+$/,"");
}

E
Erik

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

This is a pretty recent addition to javascript, and its not supported by IE.


k
kaichanvong

I had a similar issue when trying to trim a value from an input and then ask if it was equal to nothing:

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

However this threw a spanner in the works for IE6 - 8. Annoyingly enough I'd tried to var it up like so:

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

However, using jQuery's trim method, works perfectly for me in all browsers..

var originalValueTrimmed = $.trim($(this).val());              
            if (originalValueTrimmed  == "") { ... }

C
Community

I have written some code to implement the trim functionality.

LTRIM (trim left):

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

RTRIM (trim right):

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

TRIM (trim both sides):

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

OR

Regular expression is also available which we can use.

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

Useful Explanation


Your old school search and destroy code does not handle \t, \r, \n and such. Only spaces. Regexp is better if you don't feel like really putting in the effort to manually handle everything.
W
Will V King

We can get official code From the internet! Refer this:

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

Running the following code before any other code will create trim() if it's not natively available. 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, ''); }; })(); }

for more: I just found there is js project for supporting EcmaScript 5: https://github.com/es-shims/es5-shim by reading the source code, we can get more knowledge about 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);


S
Sampson

I don't think there's a native trim() method in the JavaScript standard. Maybe Mozilla supplies one, but if you want one in IE, you'll need to write it yourself. There are a few versions on this page.


M
Mark

I had the same problem in IE9 However when I declared the supported html version with the following tag on the first line before the

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

The problem was resolved.


J
Jobelle

This is because of typo error getElementByID. Change it to getElementById


S
Stephen P
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);
}

Why do a loop when you can use a simple replace, also its very bad when time is crutial, try calling this method 200 times on average size text and calling the other implementation provided by jQuery and you'll see what i am talking about :)
Because in some cases a loop is faster than a regexp. See the link that JW posted in his answer for some benchmarks, especially the comments there (since the original benchmark is quite old).
S
Sampson

Just found out that IE stops supporting trim(), probably after a recent windows update. If you use dojo, you can use dojo.string.trim(), it works cross platform.


F
FuzzyJulz

This issue can be caused by IE using compatibility mode on intranet sites. There are two ways to resolve this, you can either update IE to not use compatibility mode on your local machine (in IE11: Tools-> Compatibility View Settings -> Uncheck Display intranet sites in Compatibility View)

Better yet you can update the meta tags in your webpage. Add in:

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

What does this mean? It is telling IE to use the latest compatibility mode. More information is available in MSDN: Specifying legacy document modes