Trim vs Strip

Benchmark created by Andrew Wilson on


Setup

var strip = function(string, characters) {
      if(!characters) {
          if(typeof String.prototype.trim !== undefined) {
              // Simply use the String.trim as a default
              return string.trim();
           } else {
              // set characters to whitespaces
              characters = "\s\uFEFF\xA0";
           }
      }
      // Characters is set at this point forward
      // Validate characters just in case there are invalid usages
      var escaped = characters.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
      
      var target = new RegExp('['+ escaped +']+');
      var targetBeginning = new RegExp('^[' + escaped + ']+');
      
      // Remove the characters from the beginning of the string
      string = string.replace(targetBeginning, '');
      var i = string.length;
      // Remove the characters from the end of the string
      while (target.test(string.charAt(--i)));
      return string.slice(0, i + 1);
  };

Test runner

Ready to run.

Testing in
TestOps/sec
Trimming with trim
var trimmed = 'NothingToTrim';
trimmed.trim();
ready
Trimming with strip
var trimmed = 'NothingToTrim';
strip(trimmed);
ready
Trimming with many spaces
var trimmed = '          10 Left 20 right                  ';
trimmed.trim();
ready
Stripping with many spaces
var trimmed = '          10 Left 20 right                  ';
strip(trimmed);
ready
Stripping characters
var trimmed = 'aaaaaaaaaa10 Left 20 rightaaaaaaaaaaaaaaaaaaaa';
strip(trimmed,'a');
ready
Stripping multiple chars
var trimmed = 'a b a a a a 10 Left 20 right        b  a b      ';
strip(trimmed, 'ab ');
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Andrew Wilson on
  • Revision 2: published by Andrew Wilson on