Replaceall escape

JavaScript performance comparison

Revision 4 of this test case created by Emanuel Jackstare

Info

String replaceall ignoring regex special chars

Preparation code

<script>
window.esc = function(str) {
  return str.replace(new RegExp('\\$', 'g'), "#67")
}

window.unesc = function(str) {
  return str.replace("#67", "$");
}

var replaceAll1 = window.replaceAll1 = function(str, tofind, torep) {
  return unescape(escape(str).replace(new RegExp(escape(tofind), 'g'), torep));
}

var replaceAll3 = window.replaceAll3 = function(str, tofind, torep) {
  return unesc(esc(str).replace(new RegExp(esc(tofind), 'g'), torep))
}

var replaceAll2 = window.replaceAll2 = function(str, tofind, torep) {
    while (str.indexOf(tofind) > -1) {
        str = str.replace(tofind, torep); //using regex you end up having todo a bunch of escaping
    }
    return str;
}

var replaceAll4 = window.replaceAll4 = function(str, tofind, torep) {
    var temp;
    while ((temp = str.replace(tofind, torep)) !== str) {
        str = temp;
    }
    return str;
}

var replaceAll5 = window.replaceAll5 = function(str, tofind, torep) {
    return str.split(tofind).join(torep);
};
</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
replaceall regex escape
replaceAll1("$$testingmyreplace$/$", "$", ":)");
replaceAll1("testingmyreplace", "$", ":)");
replaceAll1("testingmyreplace$/$", "$", ":)");
pending…
replaceall loop
replaceAll2("$$testingmyreplace$/$", "$", ":)");
replaceAll2("testingmyreplace", "$", ":)");
replaceAll2("testingmyreplace$/$", "$", ":)");
pending…
regex escape
replaceAll3("$$testingmyreplace$/$", "$", ":)");
replaceAll3("testingmyreplace", "$", ":)");
replaceAll3("testingmyreplace$/$", "$", ":)");
pending…
Loop 2
replaceAll4("$$testingmyreplace$/$", "$", ":)");
replaceAll4("testingmyreplace", "$", ":)");
replaceAll4("testingmyreplace$/$", "$", ":)");
pending…
Split join
replaceAll5("$$testingmyreplace$/$", "$", ":)");
replaceAll5("testingmyreplace", "$", ":)");
replaceAll5("testingmyreplace$/$", "$", ":)");
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