Skip to content

Commit

Permalink
fix: handle extra slashes in urls (#5)
Browse files Browse the repository at this point in the history
* fix: handle extra slashes in urls

* chore: bump version

Co-authored-by: Justin Schrader <jschrader@newrelic.com>
  • Loading branch information
icd2k3 and jschrader-nr committed Apr 15, 2020
1 parent 9b3652e commit 6ae03dd
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 4 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "use-react-router-breadcrumbs",
"version": "1.0.2",
"version": "1.0.3",
"description": "A hook for displaying and setting breadcrumbs for react router",
"main": "dist/cjs/index.js",
"module": "dist/es/index.js",
Expand Down
7 changes: 7 additions & 0 deletions src/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -396,4 +396,11 @@ describe('use-react-router-breadcrumbs', () => {
expect(forwardedProps).toEqual('prop forwarding works');
});
});

describe('Edge cases', () => {
it('Should handle 2 slashes in a URL (site.com/sandwiches//tuna)', () => {
const { breadcrumbs } = render({ pathname: '/sandwiches//tuna' });
expect(breadcrumbs).toBe('Home / Sandwiches / Tuna');
});
});
});
9 changes: 6 additions & 3 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -199,17 +199,20 @@ export const getBreadcrumbs = (

pathname
.split('?')[0]
// Remove trailing slash "/" from pathname.
.replace(/\/$/, '')
// Split pathname into sections.
.split('/')
// Reduce over the sections and call `getBreadcrumbMatch()` for each section.
.reduce((previousSection: string, currentSection: string) => {
.reduce((previousSection: string, currentSection: string, index: number) => {
// Combine the last route section with the currentSection.
// For example, `pathname = /1/2/3` results in match checks for
// `/1`, `/1/2`, `/1/2/3`.
const pathSection = !currentSection ? '/' : `${previousSection}/${currentSection}`;

// Ignore trailing slash or double slashes in the URL
if (pathSection === '/' && index !== 0) {
return '';
}

const breadcrumb = getBreadcrumbMatch({
currentSection,
location,
Expand Down

0 comments on commit 6ae03dd

Please sign in to comment.