InterviewHubPRO
Section Overview
Q139

Question 139 of 521

Part 3: DOM, Event Flow, Timers & Browser APIs (104 - 173)

27%
JavaScript Internals (521 Qs)•Part 3: DOM, Event Flow, Timers & Browser APIs (104 - 173)

How do you trim a string in javascript

JavaScript provided a trim method on string types to trim any whitespaces present at the beginning or ending of the string.

javascript
  "  Hello World   ".trim(); //Hello World

If your browser(<IE9) doesn't support this method then you can use below polyfill.

javascript
  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, "");
      };
    })();
  }