@intlayer/core
Version:
Includes core Intlayer functions like translation, dictionary, and utility functions shared across multiple packages.
40 lines (38 loc) • 1.68 kB
JavaScript
import { checkIsURLAbsolute } from "../utils/checkIsURLAbsolute.mjs";
import { Locales } from "@intlayer/types";
import configuration from "@intlayer/config/built";
//#region src/localization/getLocaleFromPath.ts
/**
* Extracts the locale segment from the given URL or pathname if present.
* If no locale is present, returns the default locale (en).
*
* Example:
*
* ```ts
* getLocaleFromPath('/en/dashboard') // Returns 'en'
* getLocaleFromPath('/fr/dashboard') // Returns 'fr'
* getLocaleFromPath('/dashboard') // Returns 'en'
* getLocaleFromPath('dashboard') // Returns 'en'
* getLocaleFromPath('https://example.com/es/dashboard') // Returns 'es'
* getLocaleFromPath('https://example.com/fr/dashboard') // Returns 'fr'
* getLocaleFromPath('https://example.com/dashboard') // Returns 'en'
* ```
*
* @param inputUrl - The complete URL string or pathname to process.
* @returns The detected locale or default (en) if no locale is found
*/
const getLocaleFromPath = (inputUrl) => {
const { defaultLocale, locales } = configuration?.internationalization ?? {};
if (!defaultLocale || !locales) return Locales.ENGLISH;
const isAbsoluteUrl = checkIsURLAbsolute(inputUrl);
let fixedInputUrl = inputUrl;
if (inputUrl.endsWith("/")) fixedInputUrl = inputUrl.slice(0, -1);
const pathname = (isAbsoluteUrl ? new URL(fixedInputUrl) : new URL(fixedInputUrl, "http://example.com")).pathname;
if (!pathname.startsWith("/")) return defaultLocale;
const firstSegment = pathname.split("/")[1];
if (firstSegment && locales.includes(firstSegment)) return firstSegment;
return defaultLocale;
};
//#endregion
export { getLocaleFromPath };
//# sourceMappingURL=getLocaleFromPath.mjs.map