RegEx to match full string

I am trying to create a regex for 301s that will help me identify the url: site.com/abc/ and redirect to site.com/xyz/. I've tried regex as ^abc/? and it works fine but the problem is even urls like site.com/123/sdas/abc/213 are getting caught. How can I ensure only /abc gets matched with the full string url?


Solution 1:

Use the end of line anchor $:

^abc/$

This ensures that the exact string abc/ will be matched.

Solution 2:

$ matches end of string:

^abc/?$

Solution 3:

 const regex = /^((http[s]?|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$/;
      const str = `https://abc.xyz/upload/string/something/hds`;
      let m;

      if ((m = regex.exec(str)) !== null) {
        // The result can be accessed through the `m`-variable.
        m.forEach((match, groupIndex) => {
          console.log(`Found match, group ${groupIndex}: ${match}`);
        });
      }

in console:

Match 1 Full match 0-43 https://abc.xyz/upload/string/something/hds -Group 1. n/a https:/ -Group 2. n/a https -Group 3. n/a abc.xyz -Group 4. n/a /upload/string/something/ -Group 5. n/a /something -Group 6. n/a hds