Home > Software engineering >  replace a domain extension with a string in url
replace a domain extension with a string in url

Time:03-17

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.

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');
        }
    }

CodePudding user response:

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'));

  • Related