Search code examples
javascriptreplaceuserscripts

Replace malfunction in userscript: adds current URL in front of result


I'm trying to remove unwanted parts in outgoing links on a website with a userscript by replacing them with nothing.

jQuery(document).on("mouseenter", "a", function(event) {
    jQuery(this).prop("href", jQuery(this).prop("href").replace(/https;\/\/steamcommunity\.com\/linkfilter\/\?u=/, ""));
});

Said parts (https;//steamcommunity.com/linkfilter/?u=) get removed, but then not replaced with nothing but with the current URL.

Example:
I'm on this URL: https;//store.steampowered.com/app/1091500/Cyberpunk_2077/
There's a link ("Visit the website") to: https;//steamcommunity.com/linkfilter/?u=https;//www.cyberpunk.net
The script should change it to: https;//www.cyberpunk.net
The script does change it to: https;//store.steampowered.com/app/1091500/Cyberpunk_2077/https;//www.cyberpunk.net

If I just run the function in the browser console, it works as intended.
Input: "https;//steamcommunity.com/linkfilter/?u=https;//www.cyberpunk.net".replace(/https;\/\/steamcommunity\.com\/linkfilter\/\?u=/, "");
Output: "https;//www.cyberpunk.net"

Doesn't work with other replacements either.

jQuery(document).on("mouseenter", "a", function(event) {
    jQuery(this).prop("href", jQuery(this).prop("href").replace(/https;\/\/steamcommunity\.com\/linkfilter\/\?u=/, "TEST"));
});

Should be: TESThttps;//www.cyberpunk.net
Is: https;//store.steampowered.com/app/1091500/Cyberpunk_2077/TESThttps;//www.cyberpunk.net

Had to replace https: with https; because question was marked as "spam"...


Solution

  • This is not working because the resulting string does not start with a valid scheme, (i.e. http:// or https://) so the browser is assuming that the link is relative and prepending the current url. It would appear that the colon and slashes of the scheme are actually encoded characters and need replaced as well. See the fiddle for handling that decoding and the resulting string should pass the scheme test and everything should work as expected.

    jsfiddle.net/fw4tjvL7