Search code examples
javascriptreplacestr-replace

How can I perform a str_replace in JavaScript, replacing text in JavaScript?


I want to use str_replace or its similar alternative to replace some text in JavaScript.

var text = "this is some sample text that i want to replace";
var new_text = replace_in_javascript("want", "dont want", text);
document.write(new_text);

should give

this is some sample text that i dont want to replace

If you are going to regex, what are the performance implications in comparison to the built in replacement methods.


Solution

  • Using regex for string replacement is significantly slower than using a string replace.
    As demonstrated on JSPerf, you can have different levels of efficiency for creating a regex, but all of them are significantly slower than a simple string replace. The regex is slower because:

    Fixed-string matches don't have backtracking, compilation steps, ranges, character classes, or a host of other features that slow down the regular expression engine. There are certainly ways to optimize regex matches, but I think it's unlikely to beat indexing into a string in the common case.

    For a simple test run on the JS perf page, I've documented some of the results:

    <script>
    // Setup
      var startString = "xxxxxxxxxabcxxxxxxabcxx";
      var endStringRegEx = undefined;
      var endStringString = undefined;
      var endStringRegExNewStr = undefined;
      var endStringRegExNew = undefined;
      var endStringStoredRegEx = undefined;      
      var re = new RegExp("abc", "g");
    </script>
    
    <script>
    // Tests
      endStringRegEx = startString.replace(/abc/g, "def") // Regex
      endStringString = startString.replace("abc", "def", "g") // String
      endStringRegExNewStr = startString.replace(new RegExp("abc", "g"), "def"); // New Regex String
      endStringRegExNew = startString.replace(new RegExp(/abc/g), "def"); // New Regexp
      endStringStoredRegEx = startString.replace(re, "def") // saved regex
    </script>

    The results for Chrome 68 are as follows:

    String replace:    9,936,093 operations/sec
    Saved regex:       5,725,506 operations/sec
    Regex:             5,529,504 operations/sec
    New Regex String:  3,571,180 operations/sec
    New Regex:         3,224,919 operations/sec
    

    From the sake of completeness of this answer (borrowing from the comments), it's worth mentioning that .replace only replaces the first instance of the matched character. Its only possible to replace all instances with //g. The performance trade off and code elegance could be argued to be worse if replacing multiple instances name.replace(' ', '_').replace(' ', '_').replace(' ', '_'); or worse while (name.includes(' ')) { name = name.replace(' ', '_') }