From 220602488b95748c74141d647e13114c7a4569fb Mon Sep 17 00:00:00 2001 From: Alice Koreman Date: Thu, 6 Jun 2024 09:55:31 +0200 Subject: [PATCH] feat: allow '{n}' as placeholder for translated strings (#5581) * feat: allow '{n}' as placeholder for translated strings --- src/config_test.js | 4 +++- src/lib/app_config.js | 12 +++++++++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/config_test.js b/src/config_test.js index 5305705d88b..ec0fc34637b 100644 --- a/src/config_test.js +++ b/src/config_test.js @@ -53,7 +53,8 @@ module.exports = { var nls = config.nls; config.setMessages({ foo: "hello world of $1", - test_key: "hello world for test key" + test_key: "hello world for test key", + test_with_curly_brackets: "hello world $0 of {1} and $2 to the {3} degree" }); assert.equal(nls("untranslated_key","bar $1"), "bar $1"); assert.equal(nls("untranslated_key", "bar"), "bar"); @@ -62,6 +63,7 @@ module.exports = { assert.equal(nls("untranslated_key", "$0B is $1$$", [0.11, 22]), "0.11B is 22$"); assert.equal(nls("untranslated_key_but_translated_default_string", "foo", {1: "goo"}), "hello world of goo"); assert.equal(nls("test_key", "this text should not appear"), "hello world for test key"); + assert.equal(nls("test_with_curly_brackets", "hello world $0 of {1} and $2 to the {3} degree", ["foo", "bar", "yay", "third"]), "hello world foo of bar and yay to the third degree"); }, "test: define options" : function() { var o = {}; diff --git a/src/lib/app_config.js b/src/lib/app_config.js index 041b32d51ef..5d0e076b190 100644 --- a/src/lib/app_config.js +++ b/src/lib/app_config.js @@ -158,9 +158,15 @@ class AppConfig { var translated = messages[key] || messages[defaultString] || defaultString; if (params) { - translated = translated.replace(/\$(\$|[\d]+)/g, function(_, name) { - if (name == "$") return "$"; - return params[name]; + // We support both $n or {n} as placeholder indicators in the provided translated strings + // Replace $n with the nth element in params + translated = translated.replace(/\$(\$|[\d]+)/g, function(_, dollarMatch) { + if (dollarMatch == "$") return "$"; + return params[dollarMatch]; + }); + // Replace {n} with the nth element in params + translated = translated.replace(/\{([^\}]+)\}/g, function(_, curlyBracketMatch) { + return params[curlyBracketMatch]; }); } return translated;