Useful trim prototype (function) in core javascript

Below is the most commonly used trim prototype/function in javascript. Posting for reference.

String.prototype.trim = function()	{
	return this.replace(/(^\s*)|(\s*$)/g,"")
}

You can place the above code (wrapped in <script></script>) inside <header> section of your web page or you can place it in an external javascript file which you include in the header section.

//how to use it example
var my_string = "  Hello trim me           ";
var my_string_trimmed = my_string.trim();
//my_string_trimmed now has "Hello trim me"

Very useful tool.

2 thoughts on “Useful trim prototype (function) in core javascript

  1. very bad idea. Modern browsers (ie9, ff, opera, chrome, safari) implement native trim functions.
    test for this prior replacing it:
    if (!String.prototype.trim) {

    1. @Holger – I never faced any issue while using this function. Considering the check kind of thing one could modify it to look like:

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

      Also, considering the global pattern delimiter (g) it may be slow sometimes but i don’t see any other ‘bad’ in this implementation. For a faster alternative one may consider using Douglas Crockford’s implementation(regex) which is as following:

      String.prototype.trim = function () {
      return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
      };

      I am not sure what do you mean by “native” trim function in browsers. I could not find such function at least in firefox (which i use most). Can you guide me to find one?

Leave a Reply