Skip to content

Commit

Permalink
Interpolate multiple instances of variables. (#102)
Browse files Browse the repository at this point in the history
Co-authored-by: Sasha Chedygov <schedygov@evidation.com>
  • Loading branch information
fnando and sasha-evidation authored Oct 10, 2024
1 parent 8ecf5a2 commit 6cd7e24
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 2 additions & 0 deletions __tests__/fixtures/translations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ export function translations(): { [key: string]: any } {
},
},
},

multiple_variables: "Hello, {{name}}! Your name is {{name}}.",
};

Translations["en-US"] = {
Expand Down
7 changes: 7 additions & 0 deletions __tests__/interpolation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
1 change: 1 addition & 0 deletions src/helpers/interpolate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export function interpolate(

const regex = new RegExp(
placeholder.replace(/\{/gm, "\\{").replace(/\}/gm, "\\}"),
"g",
);

message = message.replace(regex, value);
Expand Down

0 comments on commit 6cd7e24

Please sign in to comment.