Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

209
Views
Remove/replenish tailing characters from react-router-dom Routes

I have a Route: /:question/:id

What I want is if put /:questionName/:idnonsense, the nonsense gets removed automatically.

Say /how_to_do_that/123 is an available route, if /how_to_do_that/123345345345 or /how_to_do_that/123awheofhawoeiha entered in the address bar, it will revise automatically to /how_to_do_that/123. Or if I put /how_to_do_that/12, it will replenish it to /how_to_do_that/123. And redirect to /how_to_do_that/123

How am I able to do that? I am using Routes in React. I tried a whole day to make it....

I tried on youtube, their routes can do that. So https://www.youtube.com/watch?v=1fPWr0d5zBE is an available link, if you try to visit https://www.youtube.com/watch?v=1fPWr0d5zBEAHSOHOWIHFOH, it will be revised to https://www.youtube.com/watch?v=1fPWr0d5zBE and visit that link instead. But if you try to visit https://www.youtube.com/watch?v=1fPWr0d5z, that is a 404 (which I think can be improved by matching the close guess).

Does anybody know how to do that? Thanks a lot.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Well, your youtube example doesn't match what you are asking for in your question (route path params vs queryString params), but I think the answer is the same either way. You want to validate a route path parameter. Handle this in the component with a regular expression.

const regexp123 = /^123$/;

console.log(regexp123.test("123345345345"));
console.log(regexp123.test("123"));
console.log(regexp123.test("12"));

In the component the logic might look like this:

import { generatePath, useParams, useNaviate } from 'react-router-dom';

const regexp123 = /^123$/;
const params = useParams();
const navigate = useNavigate();

useEffect(() => {
  const { id } = params;
  if (!regexp123.test(id)) {
    const target = generatePath(
      "/:question/:id",
      {
        ...params,
        id: '123',
      },
    );
    navigate(target, { replace: true });
  }
}, [navigate, params]);

The gist is that the component needs to validate the path parameters manually and handle accordingly. The same for queryString parameters using the useSearchParams hook.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!