.replace() vs. .split().join() vs .replaceAll()

JavaScript performance comparison

Revision 4 of this test case created

Info

A solution for replacement of strings.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var mystring = 'okay.this.is.a.string';
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
.replace(/\./g,' ')
result = mystring.replace(/\./g,' ');
pending…
.replace(new RegExp(".","gm")," ")
result = mystring.replace(new RegExp(".","gm")," ");
pending…
.split('.').join(' ')
result = mystring.split('.').join(' ');
pending…
replaceAll-Fagner-Brack
/**
 * ReplaceAll by Fagner Brack (MIT Licensed)
 * Replaces all occurrences of a substring in a string
 */

String.prototype.replaceAll = function(token, newToken, ignoreCase) {
    var str, i = -1, _token;
    if((str = this.toString()) && typeof token === "string") {
        _token = ignoreCase === true? token.toLowerCase() : undefined;
        while((i = (
            _token !== undefined?
                str.toLowerCase().indexOf(
                            _token,
                            i >= 0? i + newToken.length : 0
                ) : str.indexOf(
                            token,
                            i >= 0? i + newToken.length : 0
                )
        )) !== -1 ) {
            str = str.substring(0, i)
                    .concat(newToken)
                    .concat(str.substring(i + token.length));
        }
    }
return str;
};

result = mystring.replaceAll('.', ' ');
pending…
while
/*
http://vhspiceros.blogspot.fi/2008/12/replace-all-en-javascript.html
*/

function replaceAll( text, busca, reemplaza ){
          while (text.toString().indexOf(busca) != -1)
              text = text.toString().replace(busca,reemplaza);
          return text;
}
result = mystring.replaceAll('.', ' ');
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment