JS Coding Questions Logo
JS Coding Questions
#135💼 Interview💻 Code

How do you trim a string in javascript

Advertisement

728x90

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

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

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

javascript
1if (!String.prototype.trim) {
2  (function () {
3  // Make sure we trim BOM and NBSP
4  var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
5  String.prototype.trim = function () {
6  return this.replace(rtrim, "");
7  };
8  })();
9  }

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 51

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
135of476