regex

Redirect Youtube channel main page to videos section the proper way using regex


I made a regex rule using Requestly that each time I get on a youtube channel it will redirect me to the videos section. The rule I made is this:

/https\:\/\/www\.youtube\.com\/channel\/(.+)/ig

Substitute with:

https://www.youtube.com/channel/$1/videos

Having this as a test string:

https://www.youtube.com/channel/random_name1234

, I get this:

https://www.youtube.com/channel/random_name1234/videos

The problem comes when I refresh the page by mistake. So, if the URL is already:

https://www.youtube.com/channel/random_name1234/videos

, I get:

https://www.youtube.com/channel/random_name1234/videos/videos

If I am in the playlists section of the channel and I refresh the page, I get:

https://www.youtube.com/channel/random_name1234/playlists/videos

How can I address this problem by modifying the regex pattern? I had several attempts at it, but I failed since I'm not so good at regex.

Thank you!


Solution

  • The issue is that .* is going to match on anything -- including if you're already on the /videos page, or some other section like /playlist, /community, etc.

    You can make the regex more restrictive by saying "only match on non-forward-slash characters", to ensure that the URL in question is actually the main channel page.

    Try this:

    /https\:\/\/www\.youtube\.com\/channel\/([^\/]+)\/?$/ig