const strip = (str) => str.replace(/\/?index$/, '');
strip('en/index');
strip('index');
strip('en/guides/getting-started');
const strip = (str) => str === 'index' ? '' : str.endsWith('/index') ? str.slice(0, -6) : str;
strip('en/index');
strip('index');
strip('en/guides/getting-started');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
RegExp replace | |
String ops |
Test name | Executions per second |
---|---|
RegExp replace | 4351416.0 Ops/sec |
String ops | 11359012.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
What is tested?
The provided benchmark tests two approaches to remove the last part of a string: using regular expressions (RegExp replace
) and using basic string operations (String ops
).
Options compared
There are two options being compared:
replace()
method with a regular expression to remove the last part of the string. The regular expression /\\/?index$/
matches any character that is escaped (i.e., preceded by a backslash) or is literally the last occurrence of the substring "index".Pros and Cons
RegExp Replace:
Pros:
Cons:
.
, ?
) to prevent unexpected behavior.String Ops:
Pros:
Cons:
.endsWith()
).Library used
In this benchmark, the replace()
method is used, which is a built-in JavaScript method. No external library is required.
Special JS feature or syntax
There are no special JavaScript features or syntaxes used in these benchmarks beyond what is standard for modern JavaScript.
Other alternatives
Other approaches to remove the last part of a string might include:
substring()
method to extract a subset of characters from the original string.slice()
method to extract a subset of characters from the original string, similar to String Ops
.\bindex\b
or [^\w]
, to remove the last part of the string.These alternatives may have their own pros and cons, which would be worth exploring in a separate benchmarking exercise.