Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Escape special regex characters when matching routes #766

Merged
merged 2 commits into from
Aug 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/js/Route.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ export default class Route {
// Transform the route's template into a regex that will match a hydrated URL,
// by replacing its parameter segments with matchers for parameter values
const pattern = this.template
.replace(/[.*+$()[\]]/g, '\\$&')
.replace(/(\/?){([^}?]*)(\??)}/g, (_, slash, segment, optional) => {
const regex = `(?<${segment}>${
this.wheres[segment]?.replace(/(^\^)|(\$$)/g, '') || '[^/?]+'
Expand Down
11 changes: 11 additions & 0 deletions tests/js/route.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,10 @@ const defaultZiggy = {
},
parameters: ['storefront', 'catalog_uri'],
},
regexSpecialChars: {
uri: 'test.*+$()[]/{slug}',
methods: ['GET', 'HEAD'],
},
},
};

Expand Down Expand Up @@ -1439,6 +1443,13 @@ describe('current()', () => {
expect(route().current('events.venues.*')).toBe(false);
});

test('matches route with escaped Regex special characters', () => {
global.window.location.pathname = '/test.*+$()[]/1';

expect(route().current()).toBe('regexSpecialChars');
expect(route().current('regexSpecialChars')).toBe(true);
});

test.skip('can unresolve arbitrary urls to names and params', () => {
const resolved = route().unresolve('https://ziggy.dev/events/1/venues?test=yes');
expect(resolved).toStrictEqual({
Expand Down