@intlayer/core
Version:
Includes core Intlayer functions like translation, dictionary, and utility functions shared across multiple packages.
55 lines (53 loc) • 2.67 kB
JavaScript
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
const require_utils_checkIsURLAbsolute = require('../utils/checkIsURLAbsolute.cjs');
let __intlayer_config_built = require("@intlayer/config/built");
__intlayer_config_built = require_rolldown_runtime.__toESM(__intlayer_config_built);
//#region src/localization/getPathWithoutLocale.ts
/**
* Removes the locale segment from the given URL or pathname if present.
* Also removes locale from search parameters if present.
*
* This function get the locales from the configuration if not provided.
*
* Example:
*
* ```ts
* getPathWithoutLocale('/en/dashboard') // Returns '/dashboard'
* getPathWithoutLocale('/fr/dashboard') // Returns '/dashboard'
* getPathWithoutLocale('/dashboard') // Returns '/dashboard'
* getPathWithoutLocale('dashboard') // Returns 'dashboard'
* getPathWithoutLocale('/dashboard?locale=fr') // Returns '/dashboard'
* getPathWithoutLocale('https://example.com/en/dashboard') // Returns 'https://example.com/dashboard'
* getPathWithoutLocale('https://example.com/fr/dashboard') // Returns 'https://example.com/dashboard'
* getPathWithoutLocale('https://example.com/dashboard') // Returns 'https://example.com/dashboard'
* getPathWithoutLocale('https://example.com/dashboard?locale=fr') // Returns 'https://example.com/dashboard'
* ```
*
* @param inputUrl - The complete URL string or pathname to process.
* @param locales - Optional array of supported locales. Defaults to `localesDefault`.
* @returns The URL string or pathname without the locale segment or locale search parameter.
*/
const getPathWithoutLocale = (inputUrl, locales = __intlayer_config_built.default?.internationalization?.locales) => {
const isAbsoluteUrl = require_utils_checkIsURLAbsolute.checkIsURLAbsolute(inputUrl);
let fixedInputUrl = inputUrl;
if (inputUrl.endsWith("/")) fixedInputUrl = inputUrl.slice(0, -1);
const url = isAbsoluteUrl ? new URL(fixedInputUrl) : new URL(fixedInputUrl, "http://example.com");
const pathname = url.pathname;
if (!pathname.startsWith("/")) url.pathname = `/${pathname}`;
const pathSegments = pathname.split("/");
const firstSegment = pathSegments[1];
if (locales?.includes(firstSegment)) {
pathSegments.splice(1, 1);
url.pathname = pathSegments.join("/") ?? "/";
}
const searchParams = new URLSearchParams(url.search);
if (searchParams.has("locale")) {
searchParams.delete("locale");
url.search = searchParams.toString();
}
if (isAbsoluteUrl) return url.toString();
return url.toString().replace("http://example.com", "");
};
//#endregion
exports.getPathWithoutLocale = getPathWithoutLocale;
//# sourceMappingURL=getPathWithoutLocale.cjs.map