Trim vs Strip (v2)

Revision 2 of this benchmark created by Andrew Wilson on


Description

This is an implementation of strip that is meant to be used over trim for its advanced features as well as a poly-fill

Preparation HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.string/3.0.2/underscore.string.min.js"></script>

Setup

var strip = function(string, characters) {
        'use strict';
        if(!characters) {
            if(typeof String.prototype.trim !== undefined) {
                // Simply use the String.trim as a default
                return String.prototype.trim.call(string);
             } 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 + ']+|[' + escaped + ']+$');
        
        // Remove the characters from the beginning of the string
        string = string.replace(target, '');
    };

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
Underscore.string trimming
var trimmed = 'a b a a a a 10 Left 20 right        b  a b      '; s.trim(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