userscript to remove consistent string from URLs

Viewed 24

I am trying to write a simple userscript for practice with this concept. Please forgive this example, but its the first one I can think of.

So on sports illistrated swimsuit images, they deliver a smaller than original image. Here is a sample URL: (might be nsfw if you consider bikinis nsfw) https://www.si.com/.image/c_limit%2Ccs_srgb%2Cq_auto:good%2Cw_385/MTY4MjU5NDM2MzkyMDMyMTI5/chrissy-teigen6jpg.webp

So in order to manipulate the URL to load the original size image, I need to remove this exact string from every image URL I load on this website: "c_limit%2Ccs_srgb%2Cq_auto:good%2Cw_385/"

Removing that string from the image URL serves the largest image. I am trying to write a userscript to automatically remove that, but I struggling with where to start. I have basics in JS down (I love writing bookmarklets) but am struggling to write a userscript.

Thanks.

2 Answers

Check if the undesirable substring exists in the window.location.href, and if it does, .replace that part with the empty string.

// ==UserScript==
// @name             Full SI images
// @include          https://www.si.com/*
// @grant            none
// ==/UserScript==

if (window.location.href.includes('c_limit')) {
  window.location.href = window.location.href.replace('c_limit%2Ccs_srgb%2Cq_auto:good%2Cw_385/', '');
}

To make it more dynamic in terms of coding, you might wanna try to enhance the possibility of passing a not-a-hard-code fixed substring that you would want to remove from the url ("c_limit%2Ccs_srgb%2Cq_auto:good%2Cw_385/") since this might vary from photo to photo, right?. what if we could remove this substring regardless its string content?

The common substring part is c_limit hence we could use this as our starting point to get the rest of the substring after this(including this part) until we find the dimension digits just before the first forward slash after this whole substring on this URL. Check this example out, pal. Hope it helps understand this concept better! Cheers!

let urlStr = "https://swimsuit.si.com/.image/c_limit%2Ccs_srgb%2Cq_auto:good%2Cw_700/MTg5NTA4MDYzMTE0MzA2ODIy/kim_si_domrep_jan2022_s9_01237_updated2_wmweb.webp";

const highResUrlStr = urlStr.replace(/c_limit.*\d[/]/g, "");
console.log(highResUrlStr);
Related