Search code examples
reactjsant-design-pro

How to get the last part of the current URL in ant design


I'm making an edit form in ant design and I want to get the id passed from the following route in the component

      {
        path: '/post/edit/:id',
        name: 'edit',
        hideInMenu: true,
        component: './Post/PostForm'
      },

Solution

  • I use the following function:

    export function getLastPart() {
      const parts = window.location.href.split('/');
      return parts[parts.length - 1];
    }
    

    Then, in the component, you need to check that the last part is an actual ID. I, for instance, use UUIDs, so I also use the following function:

    const uuidReg = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
    
    export function isUuid(path) {
      return uuidReg.test(path);
    }