Skip to content

Commit

Permalink
refactor: re-use existed escapeRegex (#34470)
Browse files Browse the repository at this point in the history
## 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.
  • Loading branch information
SukkaW committed Feb 28, 2022
1 parent 7f9b476 commit 7ca78dd
Showing 1 changed file with 4 additions and 8 deletions.
12 changes: 4 additions & 8 deletions 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) {
Expand All @@ -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('')
Expand Down Expand Up @@ -92,7 +88,7 @@ export function getParametrizedRoute(route: string) {
: `/(?<${cleanedKey}>.+?)`
: `/(?<${cleanedKey}>[^/]+?)`
} else {
return `/${escapeRegex(segment)}`
return `/${escapeStringRegexp(segment)}`
}
})
.join('')
Expand Down

0 comments on commit 7ca78dd

Please sign in to comment.