Skip to content

Commit 23bdec6

Browse files
authored
perf(shared): reduce regexp match usage (#1315)
1 parent 3382bb1 commit 23bdec6

File tree

5 files changed

+13
-8
lines changed

5 files changed

+13
-8
lines changed

packages/shared/src/utils/ensureEndingSlash.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@
22
* Ensure a url string to have ending slash /
33
*/
44
export const ensureEndingSlash = (str: string): string =>
5-
/(\.html|\/)$/.test(str) ? str : str + '/'
5+
str[str.length - 1] === '/' || str.endsWith('.html') ? str : `${str}/`

packages/shared/src/utils/ensureLeadingSlash.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@
22
* Ensure a url string to have leading slash /
33
*/
44
export const ensureLeadingSlash = (str: string): string =>
5-
str.replace(/^\/?/, '/')
5+
str[0] === '/' ? str : `/${str}`
Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
/**
22
* Remove ending slash / from a string
33
*/
4-
export const removeEndingSlash = (str: string): string => str.replace(/\/$/, '')
4+
export const removeEndingSlash = (str: string): string =>
5+
str[str.length - 1] === '/' ? str.slice(0, -1) : str

packages/shared/src/utils/removeLeadingSlash.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@
22
* Remove leading slash / from a string
33
*/
44
export const removeLeadingSlash = (str: string): string =>
5-
str.replace(/^\//, '')
5+
str[0] === '/' ? str.slice(1) : str
Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
1-
export const resolveRoutePathFromUrl = (url: string, base = '/'): string =>
2-
url
1+
export const resolveRoutePathFromUrl = (url: string, base = '/'): string => {
2+
const pathname = url
33
// remove url origin
44
.replace(/^(https?:)?\/\/[^/]*/, '')
5-
// remove site base
6-
.replace(new RegExp(`^${base}`), '/')
5+
6+
// remove site base
7+
return pathname.startsWith(base)
8+
? `/${pathname.slice(base.length)}`
9+
: pathname
10+
}

0 commit comments

Comments
 (0)