Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

replace a domain extension with a string in url

I have a string like below

https://static.example.com/uploads/image-85b2-27ee598edd99-professional-clients-jpg 

What I want is to replace .com/ with .com/resize/100x/uploads/image-85b2-27ee598edd99-professional-clients-jpg.

As you can see, the rest of the url is the same I just added /resize/100x/ after .com.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Now these links could come with any domain extension such as .io, .com, .app, .net, .gov etc etc.

I need something that works with all of them. I have the below solution but it only works for .io and .com. If I keep doing the same way then below function could easily get messy. Any idea how to accomplish this maybe through RegExp?

const addStr = (url) => {
        if (url.includes('io')) {
            return url.replace('.io', '.io/resize/100x');
        }

        if (url.includes('com')) {
            return url.replace('.com', '.com/resize/100x');
        }
    }

>Solution :

Match any url till first / and append your /resize/100x/

const addStr = (url) => {
  return url.replace(/(https?:\/\/.*?)\//, '$1/resize/100x/');
}

console.log(addStr('http://static.example.com/uploads/image-85b2-27ee598edd99-professional-clients-jpg'));
console.log(addStr('https://static.example.io/uploads/image-85b2-27ee598edd99-professional-clients-jpg'));
console.log(addStr('https://static.example.co.uk/uploads/image-85b2-27ee598edd99-professional-clients-jpg'));

OR use URL api

const addStr = (urlStr) => {
  let url = new URL(urlStr);
  url.pathname = '/resize/100x' + url.pathname;

  return url.toString();
}

console.log(addStr('http://static.example.com/uploads/image-85b2-27ee598edd99-professional-clients-jpg'));
console.log(addStr('https://static.example.io/uploads/image-85b2-27ee598edd99-professional-clients-jpg'));
console.log(addStr('https://static.example.co.uk/uploads/image-85b2-27ee598edd99-professional-clients-jpg'));
console.log(addStr('http://localhost/uploads/image-85b2-27ee598edd99-professional-clients-jpg'));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading