In modern web or mobile development, working with dynamic URLs is common — especially when environments (development, staging, production) have different base URLs but share similar API paths. One useful helper function is replacing just the base URL of an existing URL string while preserving its path and query parameters. Here’s a handy utility function to do just that: export const replaceBaseUrl = (oldUrl, newUrl) => { try { const parser = new URL(oldUrl); // Parse the original URL const newUrlObject = new URL(parser?.pathname, newUrl); // Replace the base URL while keeping the path return newUrlObject?.toString(); // Return the updated URL as a string } catch (error) { // You can log or handle errors here console.error("Invalid URL:", error); return null; } };

May 16, 2025 - 12:26
 0

In modern web or mobile development, working with dynamic URLs is common — especially when environments (development, staging, production) have different base URLs but share similar API paths. One useful helper function is replacing just the base URL of an existing URL string while preserving its path and query parameters.

Here’s a handy utility function to do just that:

export const replaceBaseUrl = (oldUrl, newUrl) => {
  try {
    const parser = new URL(oldUrl); // Parse the original URL
    const newUrlObject = new URL(parser?.pathname, newUrl); // Replace the base URL while keeping the path
    return newUrlObject?.toString(); // Return the updated URL as a string
  } catch (error) {
    // You can log or handle errors here
    console.error("Invalid URL:", error);
    return null;
  }
};