platform-bible-utils
    Preparing search index...

    Function formatReplacementStringToArray

    • Replaces each {key} in str with replacers[key], and unescapes \{/\}. An unknown key is replaced by the key text itself, and empty braces {} drop out leaving the surrounding text. Adjacent strings are concatenated into one array entry, so a replacer that is not a string stays its own entry — which is how a React element survives being substituted into a localized template.

      Type Parameters

      • T = unknown

      Parameters

      • str: string

        String containing {key} placeholders

      • replacers: object | { [key: string | number]: T }

        Object whose keys are placeholder names and whose values are the replacements

      Returns (string | T)[]

      Array of the string's pieces interleaved with the replacements

      Substituting a React element — the reason this variant exists.

      <p>
      {formatReplacementStringToArray('Hi {other}! I am {name}.', {
      other: 'Billy',
      name: <span className="tw:text-red-500">Jim</span>,
      })}
      </p>
      // ['Hi Billy! I am ', <span … >Jim</span>, '.']

      Escaped braces, a non-string replacer, and an unknown key together.

      formatReplacementStringToArray('Hi {name}! I like \\{curly braces\\}. Food: {food}.', {
      name: ['Bill'],
      });
      // ['Hi ', ['Bill'], '! I like {curly braces}. Food: food.']