Belli
Belli

Reputation: 23

React router redirect whenever there is an uppercase in URL

I want to resolve whenever there is an uppercase in the URL it needs to redirect to the URL with lowercase.

I'm facing some issues with the path part finding the right regex.

The regex /:url2*([A-Z])/ is only working whenever all letters are in uppercase and not in this situation /home/Support/

I tried different paths here https://pshrmn.github.io/route-tester without any luck.

This is my code

       <Route
              exact
              strict
              sensitive
              path='/:url2*([A-Z])/'
              render={props => {
                const path = props.location.pathname
                return <Redirect to={`${path.toLowerCase()}`} />
              }}
            />

Upvotes: 2

Views: 2863

Answers (3)

Marc Shepherd
Marc Shepherd

Reputation: 162

Expanding on the accepted answer for V6.x.x ...

export const RouterRedirect: FC = () => {
    const {pathname} = useLocation();

    // lowercase the url
    const urlContainsCapitalization = /([a-z]*[A-Z]+[a-z]*)/;
    if (urlContainsCapitalization.test(pathname)) {
        return <Navigate replace to={pathname.toLowerCase()} />;
    }

    // ... more redirect logic


    // if no redirecting needed, continue onto child (if applicable)
    return <Outlet />
}
<Route element={<RouterRedirect />} path={'/'}>

Upvotes: 0

Pedro Luna
Pedro Luna

Reputation: 1

The sensitive prop should solve that without the need for the custom render prop:

<Route
exact
strict
sensitive={false}
path='/:url([a-z/]*[A-Z]+[a-z/]*)/'
/>

Upvotes: 0

Karthick Vinod
Karthick Vinod

Reputation: 1437

I'm not an expert, but see if this works for you.

<Route
    exact
    strict
    sensitive
    path='/:url([a-z/]*[A-Z]+[a-z/]*)/'
    render={props => {
        const path = props.location.pathname
        return <Redirect to={`${path.toLowerCase()}`} />
    }}
/>

The regex /:url([a-z/]*[A-Z]+[a-z/]*)/ checks if there is at least one uppercase alphabet in URL.

Upvotes: 0

Related Questions