Can I store a redirected url into a variable with JavaScript?

Viewed 108

I'm working on a Discordbot that takes links to music posted in a channel and stores them in an array. I'm using it to create a queue of all the submitted tracks.

Most people link SoundCloud or YouTube links. Which is working fine so far. But sometimes people post a link starting with https://soundcloud.app.goo.gl Which redirects to the actual https://soundcloud.com/username/track

Same thing with https://youtu.be which redirects to https://youtube.com/etcetc

const client_2 = new Discord.Client();    
client_2.on('message', async (msg) => {
const linksubmit = "https://";
if (msg.content.startsWith(linksubmit)) {
let submit = msg.toString();
    }
}

This stores any posted link into the variable submit. But is there a way to find the redirect url, and then store it into the variable? (with JavaScript)

1 Answers

What I can think of is using the replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced [read more]. so you can do script to rewrite your links were it changes to fit your format, like this:

var URLRewriter = function(a, b) {
    $('a[href*="' + a + '"]').each(function() {
        $(this).attr('href', $(this).attr('href').replace(a, b));
    });
};

URLRewriter('youtu.be', 'youtube.com');

Related