Search code examples
javascriptbookmarklet

Replacing separate parts of an URL with Javascript


I'm trying to make a bookmarklet that will take part of an URL and redirect to the new URL, but I need to change two parts of the URL that are separate.

The base URL could be:

78.media.tumblr.com/fc87fac5ea0d88e1e22a214d25a169ee/tumblr_p3fjmdiF7f1r9qk1io1_1280.png

I need it to end like this:

s3.amazonaws.com/data.tumblr.com/fc87fac5ea0d88e1e22a214d25a169ee/tumblr_p3fjmdiF7f1r9qk1io1_raw.png

So I need to replace "78.media.tumblr.com" and "1280"

I've tried coming up with something using window.location.assign and location.href.replace but I'm pretty new and couldn't figure it out.


Solution

  • You can do this with regex and window.location.href. This is assuming you are only looking at tumbler though. If you're not, there would be another step in the regex.

    // first get the url
    var url = window.location.href;
    
    // Use regex to keep only the parts we want and replace the others
    var newUrl = url.replace(/.*(\.tumblr.*\_).*(\..*)/, 'http://s3.amazonaws.com/data$1raw$2')
    
    // go to the new page
    window.location.href = newUrl;