var string = '-firsQWEtDeadlineRQWEeminderData__PS__assignment__PS__perEntityTQWE ype__PS__Applicant__PS__hasDeadline QWE'
var regExp = new RegExp(/QWE|__PS__/gi);
var res = string.replace(regExp, '.')
var res = string.replace('__PS__', '').replace('QWE', '')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
replace by regex | |
replace via string |
Test name | Executions per second |
---|---|
replace by regex | 4019463.5 Ops/sec |
replace via string | 11207685.0 Ops/sec |
This benchmark compares two ways of replacing substrings within a given string:
1. Using Regular Expressions:
var res = string.replace(regExp, '.')
replace()
method in conjunction with a regular expression (regExp
) to find and replace all occurrences of "QWE" or "PS" within the string
variable with a dot (.
).2. Using String Replacements:
var res = string.replace('__PS__', '').replace('QWE', '')
replace()
calls on the string
. First, it replaces all instances of "PS" with an empty string. Then, it replaces all occurrences of "QWE" with an empty string.Pros and Cons:
Regular Expressions (Regex):
String Replacements:
replace()
method is highly optimized for this.Other Considerations:
Let me know if you'd like to explore any aspect of this in more detail!