1

I need the trim() function in IE8 but it's only available in IE9. How do I add it myself to IE8? I've heard of shimming or something similar but how does it work?

I'm currently writing this code:

var trim = String.trim || function (str) {
    return x.replace(/^\s+|\s+$/gm,'');
}

But then I need to replace all str_variable.trim() with trim(str_variable). How else can I write trim function and add it to String?

bodacydo
  • 75,521
  • 93
  • 229
  • 319
  • change "var trim = String.trim ||" to "String.prototype.trim=". this is safe to do, but your regexp is slow and busted... – dandavis Oct 12 '14 at 03:12
  • http://stackoverflow.com/questions/8392035/javascript-add-method-to-string-class – Reeling Oct 12 '14 at 03:13

1 Answers1

1
String.prototype.trim = String.prototype.trim || function () {
    return this.replace(/^\s+|\s+$/gm,'');
}

however, I question if this covers the same functionality as the native method.

Better to use the polyfill at MDN:

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, "");
    }
  })();
}
spender
  • 117,338
  • 33
  • 229
  • 351