Skip to content

Commit b8a9a89

Browse files
authored
perf: refactor escapeRegExp and removeDuplicateSlashes functions (#388)
* perf: refactor escapeRegExp and removeDuplicateSlashes functions * perf: replace includes with indexOf
1 parent a90f0fd commit b8a9a89

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

index.js

+12-2
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ const { safeDecodeURI, safeDecodeURIComponent } = require('./lib/url-sanitizer')
3838

3939
const FULL_PATH_REGEXP = /^https?:\/\/.*?\//
4040
const OPTIONAL_PARAM_REGEXP = /(\/:[^/()]*?)\?(\/?)/
41+
const ESCAPE_REGEXP = /[.*+?^${}()|[\]\\]/g
42+
const REMOVE_DUPLICATE_SLASHES_REGEXP = /\/\/+/g
4143

4244
if (!isRegexSafe(FULL_PATH_REGEXP)) {
4345
throw new Error('the FULL_PATH_REGEXP is not safe, update this module')
@@ -47,6 +49,14 @@ if (!isRegexSafe(OPTIONAL_PARAM_REGEXP)) {
4749
throw new Error('the OPTIONAL_PARAM_REGEXP is not safe, update this module')
4850
}
4951

52+
if (!isRegexSafe(ESCAPE_REGEXP)) {
53+
throw new Error('the ESCAPE_REGEXP is not safe, update this module')
54+
}
55+
56+
if (!isRegexSafe(REMOVE_DUPLICATE_SLASHES_REGEXP)) {
57+
throw new Error('the REMOVE_DUPLICATE_SLASHES_REGEXP is not safe, update this module')
58+
}
59+
5060
function Router (opts) {
5161
if (!(this instanceof Router)) {
5262
return new Router(opts)
@@ -755,11 +765,11 @@ Router.prototype.all = function (path, handler, store) {
755765
module.exports = Router
756766

757767
function escapeRegExp (string) {
758-
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
768+
return string.replace(ESCAPE_REGEXP, '\\$&')
759769
}
760770

761771
function removeDuplicateSlashes (path) {
762-
return path.replace(/\/\/+/g, '/')
772+
return path.indexOf('//') !== -1 ? path.replace(REMOVE_DUPLICATE_SLASHES_REGEXP, '/') : path
763773
}
764774

765775
function trimLastSlash (path) {

0 commit comments

Comments
 (0)