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>_x000D_
// Setup_x000D_
var startString = "xxxxxxxxxabcxxxxxxabcxx";_x000D_
var endStringRegEx = undefined;_x000D_
var endStringString = undefined;_x000D_
var endStringRegExNewStr = undefined;_x000D_
var endStringRegExNew = undefined;_x000D_
var endStringStoredRegEx = undefined; _x000D_
var re = new RegExp("abc", "g");_x000D_
</script>_x000D_
_x000D_
<script>_x000D_
// Tests_x000D_
endStringRegEx = startString.replace(/abc/g, "def") // Regex_x000D_
endStringString = startString.replace("abc", "def", "g") // String_x000D_
endStringRegExNewStr = startString.replace(new RegExp("abc", "g"), "def"); // New Regex String_x000D_
endStringRegExNew = startString.replace(new RegExp(/abc/g), "def"); // New Regexp_x000D_
endStringStoredRegEx = startString.replace(re, "def") // saved regex_x000D_
</script>
_x000D_
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(' ', '_') }