Search code examples
javascriptregexgreasemonkey

Greasemonkey script to replace all URLs on a page with a certain domain to a different one


I want to replace all links on the site https://www.reddit.com/r/videos/ that have the youtube.com or youtu.be domain with a different domain

I created this script that successfully replaces all youtube.com with youpak.com, but the youtu.be links aren't replaced for some reason

// ==UserScript==
// @name        replace r/videos youtube with youpak
// @namespace   test
// @include     https://www.reddit.com/r/videos/
// @version     1
// @grant       none
// ==/UserScript==

var links = document.getElementsByTagName('a');
var regexFull = /^https:\/\/www\.youtube\.com\/(.*)$/i;
var regexShort = /^https:\/\/\.youtu\.be\/(.*)$/i;
for (var i = 0; i < links.length; i++) {
  links[i].href = links[i].href.replace(regexFull, 'https://www.youpak.com/$1');
  links[i].href = links[i].href.replace(regexShort, 'https://www.youpak.com/watch/?v=$1');
}

An example URL for the regexFull rule would be https://www.youtube.com/watch?v=L4iyPXHM89E

I want this URL to be changed to https://www.youpak.com/watch?v=L4iyPXHM89E

This works


An example URL for the regexShort rule would be https://youtu.be/MkPU6P9OJv4 and https://youtu.be/MkPU6P9OJv4?t=10

I want this URL to be changed to https://www.youpak.com/watch?v=MkPU6P9OJv4 and https://www.youpak.com/watch?v=MkPU6P9OJv4?t=10 respectively

This doesn't work



Solution

  • Without the escaping the regexShort URL looks like

    ^https://.youtu.be/(.*)$
    

    As you can see there is an extra dot before 'youtu' that should not be there.

    Try:

    var regexShort = /^https:\/\/youtu\.be\/(.*)$/i;