0

I am currently working on a website and I want to implement a language file. Meaning, I want to be able to have a file called language.js, which contains an object of all code-generated strings.

An example:

var languageStrings = {
    welcomeMessage: "Welcome to our website, %s!",
    usernameInvalid: "The username '%s' is invalid",
}

module.exports = function(languageString, arguments) {
    // return a parsed string, using arguments
    // so require("./language")("welcomeMessage", "Cyberuben"); should output "Welcome to our website, Cyberuben!"
}

I am unsure how I would be able to achieve this in a fast but functional way. I was planning to use util.format, but this takes every replacement as a single argument, rather than a table or array. In Lua, there is unpack() (Source), which unpacks a table into separate elements. I'm wondering if there is a similar function in JavaScript, or if there are better ways of handling the formatting of an unknown amount of variables to a string

4

1 回答 1

0

试试https://github.com/alexei/sprintf.js它支持数组的传递。例如

vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd']);
于 2014-07-31T03:00:02.807 回答