From 7ca78dd036cd3cfe04b9cf29e669d93126be1c9c Mon Sep 17 00:00:00 2001 From: Sukka Date: Tue, 1 Mar 2022 03:50:57 +0800 Subject: [PATCH] refactor: re-use existed escapeRegex (#34470) ## Bug - [ ] Related issues linked using `fixes #number` - [ ] Integration tests added - [ ] Errors have helpful link attached, see `contributing.md` ## Feature - [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. - [ ] Related issues linked using `fixes #number` - [ ] Integration tests added - [ ] Documentation added - [ ] Telemetry added. In case of a feature if it's used or not. - [ ] Errors have helpful link attached, see `contributing.md` ## Documentation / Examples - [x] Make sure the linting passes by running `yarn lint` `escape-regex.ts` will always be included in the bundle, so not re-using it actually makes the size larger. --- packages/next/shared/lib/router/utils/route-regex.ts | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/packages/next/shared/lib/router/utils/route-regex.ts b/packages/next/shared/lib/router/utils/route-regex.ts index a3a24dc755b0..ca26d12a1e1f 100644 --- a/packages/next/shared/lib/router/utils/route-regex.ts +++ b/packages/next/shared/lib/router/utils/route-regex.ts @@ -1,15 +1,11 @@ +import { escapeStringRegexp } from '../../escape-regexp' + interface Group { pos: number repeat: boolean optional: boolean } -// this isn't importing the escape-string-regex module -// to reduce bytes -function escapeRegex(str: string) { - return str.replace(/[|\\{}()[\]^$+*?.-]/g, '\\$&') -} - function parseParameter(param: string) { const optional = param.startsWith('[') && param.endsWith(']') if (optional) { @@ -34,7 +30,7 @@ export function getParametrizedRoute(route: string) { groups[key] = { pos: groupIndex++, repeat, optional } return repeat ? (optional ? '(?:/(.+?))?' : '/(.+?)') : '/([^/]+?)' } else { - return `/${escapeRegex(segment)}` + return `/${escapeStringRegexp(segment)}` } }) .join('') @@ -92,7 +88,7 @@ export function getParametrizedRoute(route: string) { : `/(?<${cleanedKey}>.+?)` : `/(?<${cleanedKey}>[^/]+?)` } else { - return `/${escapeRegex(segment)}` + return `/${escapeStringRegexp(segment)}` } }) .join('')