Search code examples
regexreactjsurlreact-routeruppercase

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()}`} />
              }}
            />


Solution

  • 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.