Skip to content

Commit

Permalink
feat: allow '{n}' as placeholder for translated strings
Browse files Browse the repository at this point in the history
  • Loading branch information
akoreman committed Jun 5, 2024
1 parent a3277ea commit 09175fa
Showing 2 changed files with 12 additions and 4 deletions.
4 changes: 3 additions & 1 deletion src/config_test.js
Original file line number Diff line number Diff line change
@@ -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"
});
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", ["foo", "bar", "yay"]), "hello world foo of bar and yay");
},
"test: define options" : function() {
var o = {};
12 changes: 9 additions & 3 deletions src/lib/app_config.js
Original file line number Diff line number Diff line change
@@ -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;

0 comments on commit 09175fa

Please sign in to comment.