Tag Archives: regex

2019 JavaScript String.replace() regex vs substring

Having done a bunch of HTML5/js work recently, I was curious about regex performance, especially in trivial cases where the power of regular expressions is not needed and a simple string substitution would suffice. I see regexes being used and recommended all over the web for simple string search-and-replace operations, and I typically regard that as bad advice, opting for the simpler substring-based substitution in my own code. But that makes the assumption that browser regex engines are not optimized to recognize simple string substitutions and use the simpler algorithm.

So it was time for a benchmark! It’s really simple, just replacing one word with another in a sentence that only has one occurrence of the search word.

Here are my results on Windows 10 across Edge, Firefox, and Chrome:

I was not surprised to see regex be from 75-97% slower in Firefox and Edge… but I was surprised to see regexes be 75%+ faster on Chrome!! That V8 regex engine must be highly optimized for simple regex cases!

I created a jsperf test case here – feel free to try it yourself and let me know what you get!

Documentation for String.replace() is here.