Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added slug utility function #14

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/getLocale.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,20 @@ export function getLocale(url: URL): string | undefined {
// otherwise, it must be a defaultLocale or other url
return undefined;
}

/**
* @returns locale key or undefined if defaultLocale
*/
export function getLocaleFromSlug(slug: string): string | undefined {

if(slug?.length > 0 && slug[0] === "/") {
slug = slug.slice(1);
}

const pathSlices = slug.split("/");
if (pathSlices.length > 1) {
return pathSlices[0];
}

return undefined;
}
26 changes: 26 additions & 0 deletions src/getUrlWithoutLocale.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,29 @@ export function getUrlWithoutLocale(url: URL): string {
// otherwise, it must be a defaultLocale or other url
return url.pathname;
}

/**
* @returns url without locale prefix, "/es/about" => "/about"
*/
export function getUrlWithoutLocaleFromSlug(slug: string): string {
if(slug?.length === 0 ){
return "/";
}

if(slug[0] !== "/") {
slug = "/" + slug;
}

// avoid catching urls that start with "/en" like "/enigma"
if(slug.length === 3) {
return "/";
}

if (slug[0] === "/" && slug[3] === "/") {
// catch all "/fr/**/*" urls
return slug.slice(3);
}

// otherwise, it must be a defaultLocale or other url
return slug;
}
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
export { i18n, i18n as default } from "./integration";
export { i18nMiddleware } from "./middleware";
export { defaultLocaleSitemapFilter } from "./defaultLocaleSitemapFilter";
export { getLocale } from "./getLocale";
export { getLocale, getLocaleFromSlug } from "./getLocale";
export { getLocaleUrlPrefix } from "./getLocaleUrlPrefix";
export { getUrlWithoutLocale } from "./getUrlWithoutLocale";
export { getUrlWithoutLocale, getUrlWithoutLocaleFromSlug } from "./getUrlWithoutLocale";
export { defaultI18nConfig, defaultI18nMiddlewareConfig } from "./configs";
export type {
UserI18nConfig,
Expand Down