'How to listen for string after subdirectory website?

I need to run a JavaScript function when someone goes to https://website.com/custom/U1BJR09U. The U1BJR09U could be any string, but it needs to be passed on to the function. How should I go about implementing this?



Solution 1:[1]

Assuming that all traffic is redirected to a single point that serves a main file handling the URL changes, this should do it:

const hasCustom = window.location.pathname.match(/^\/custom\/([0-9A-Z]+)$/);
if (hasCustom && hasCustom[1]) {
    const myString = hasCustom[1];
    /* Do something with myString here */
}

Explanation of the regexp:

  • ^ starts with\/ (escaped slash)
  • follows with custom
  • has \/ (another slash)
  • Matches ([0-9A-Z]+) numbers and uppercase letters
  • The string ends after numbers and uppercase letters

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 savageGoat