<!--your preparation HTML code goes here-->
var str = 'Hello {first} {last}. Your first name is {first} and last name is {last}.'
str = str.replaceAll(new RegExp('{first}', 'g'), 'John')
str = str.replaceAll(new RegExp('{last}', 'g'), 'Doe')
str = str.replaceAll('{first}', 'John')
str = str.replaceAll('{last}', 'Doe')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
regex | |
string |
Test name | Executions per second |
---|---|
regex | 3249923.0 Ops/sec |
string | 5265757.5 Ops/sec |
The benchmark presented compares two methods for performing string replacements in JavaScript: using regular expressions (regex) and using the direct string method String.prototype.replaceAll
.
replaceAll
.{first}
and {last}
) meant to be replaced with actual names.Regex Test
str = str.replaceAll(new RegExp('{first}', 'g'), 'John');
str = str.replaceAll(new RegExp('{last}', 'g'), 'Doe');
replaceAll
method with a regular expression. The regular expression new RegExp('{first}', 'g')
matches all occurrences of {first}
and replaces them with 'John', while {last}
is replaced with 'Doe'.String Test
str = str.replaceAll('{first}', 'John');
str = str.replaceAll('{last}', 'Doe');
String.prototype.replaceAll
method directly with string literals. It simply searches for the specified substrings ({first}
and {last}
) and replaces them with 'John' and 'Doe', respectively.Regex Approach:
Pros:
Cons:
String Approach:
Pros:
Cons:
map
) for large datasets where replacements must occur conditionally based on certain criteria or using third-party libraries designed for enhanced string manipulation.In conclusion, this benchmark serves to highlight the practical differences between regex and simple string replacement in JavaScript, emphasizing performance versus functionality—the choice heavily depends on the specific use case and requirements of the application being developed.