From 6cd7e24bc9e8473acc153e7b89e252bb1f793e6b Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Thu, 10 Oct 2024 15:13:39 -0700 Subject: [PATCH] Interpolate multiple instances of variables. (#102) Co-authored-by: Sasha Chedygov --- CHANGELOG.md | 2 ++ __tests__/fixtures/translations.ts | 2 ++ __tests__/interpolation.test.ts | 7 +++++++ src/helpers/interpolate.ts | 1 + 4 files changed, 12 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index da990ff..b7b8b56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,8 @@ project adheres to [Semantic Versioning](http://semver.org/). ## Unreleased - [Removed] Remove `I18n#availableLocales`, as it's no used anywhere. +- [Changed] `I18n.t` now replaces all instances of a placeholder in a + translation. ## v4.4.3 - Feb 15, 2024 diff --git a/__tests__/fixtures/translations.ts b/__tests__/fixtures/translations.ts index 1b68ca2..6f49179 100644 --- a/__tests__/fixtures/translations.ts +++ b/__tests__/fixtures/translations.ts @@ -49,6 +49,8 @@ export function translations(): { [key: string]: any } { }, }, }, + + multiple_variables: "Hello, {{name}}! Your name is {{name}}.", }; Translations["en-US"] = { diff --git a/__tests__/interpolation.test.ts b/__tests__/interpolation.test.ts index eca1319..0b189fc 100644 --- a/__tests__/interpolation.test.ts +++ b/__tests__/interpolation.test.ts @@ -15,6 +15,13 @@ test("performs multiple interpolations", () => { expect(actual).toEqual("John Doe is 27-years old"); }); +test("interpolates multiple instances of each variable", () => { + const i18n = new I18n(translations()); + const actual = i18n.t("multiple_variables", { name: "John Doe" }); + + expect(actual).toEqual("Hello, John Doe! Your name is John Doe."); +}); + test("outputs missing placeholder message if interpolation value is missing", () => { const i18n = new I18n(translations()); const actual = i18n.t("greetings.name"); diff --git a/src/helpers/interpolate.ts b/src/helpers/interpolate.ts index d62716d..d462d3d 100644 --- a/src/helpers/interpolate.ts +++ b/src/helpers/interpolate.ts @@ -46,6 +46,7 @@ export function interpolate( const regex = new RegExp( placeholder.replace(/\{/gm, "\\{").replace(/\}/gm, "\\}"), + "g", ); message = message.replace(regex, value);