0

I have a language string which need be used with sprintf :

COM_COMPONENT_UPLOADED_LABEL_ERROR_REACHED_MAX_NUMBER_FILES = "You have reached the maximum number of files allowed (maximum allowed are %d files)"

This string is used in javascript part so how to use Text::sprintf with Text::script ?

1 Answer 1

1

There is no built-in function in Joomla and JS has no equivalent of sprintf(). You have to write your own. It may be impractical to try mimic PHP in JS so instead you could write a simplified version for your use case. For example, Media component has this code which just replaces most commonly used %s and %d specifiers:

const Translate = {
    // Translate from Joomla text
    translate: (key) => Joomla.Text._(key, key),
    sprintf: (string, ...args) => {
      const newString = Translate.translate(string);
      let i = 0;
      return newString.replace(/%((%)|s|d)/g, (m) => {
        let val = args[i];

        if (m === '%d') {
          val = parseFloat(val);
          if (Number.isNaN(val)) {
            val = 0;
          }
        }
        i += 1;
        return val;
      });
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.