A plain-ASCII formula, e.g. "C6H15NO3.5H3PO4"
The formula with subscripted atom counts and adduct dots, e.g. "C₆H₁₅NO₃⋅5H₃PO₄"
formatFormula("C6H15NO3") // "C₆H₁₅NO₃"
formatFormula("C6H15NO3.H3PO4") // "C₆H₁₅NO₃⋅H₃PO₄"
formatFormula("C6H15NO3.5H3PO4") // "C₆H₁₅NO₃⋅5H₃PO₄"
formatFormula("NaOH") // "NaOH"
export function formatFormula(formula: string): string {
return (
formula
// 1. period(s) between formula units → adduct dot
.replace(new RegExp(`(${TARGET_ADDUCT_DOTS.join('|')})`, 'g'), ADDUCT_DOT)
// 2. a run of digits directly after an atom (letter), ) or ] → subscript.
// Digits after the start, a space, or the adduct dot are stoichiometric
// coefficients, so their preceding char isn't a letter/bracket → skipped.
.replace(/(?<=[A-Za-z)\]])\d+/g, subscript)
);
}
Formats a plain-ASCII chemical formula with proper Unicode notation: periods that join formula units become an adduct/hydrate dot (⋅), and atom-count digits become subscripts. Digits that are leading stoichiometric coefficients — those at the start of a unit, after a space, or right after the adduct dot — are left full-size, since their preceding character isn't an atom or bracket. Intended for formulas that arrive as plain text (no
<sub>markup); tagged formulas should go through findFormulaInHtml instead.