ChemPal Documentation - v1.6.0
    Preparing search index...

    Function parsePurity

    • Extracts a purity percentage from a string. Suppliers commonly bake the purity into a product name or grade label (e.g. "Sodium borohydride, min 95%"), so this finds the first percentage and returns it as a number when it falls within the valid (0, 100] range — matching the values ProductBuilder.setPurity accepts. Returns nothing when no valid percentage is present.

      Tolerates the shapes suppliers use around the number: a leading qualifier (≥99.8%), a European comma decimal (99,5 %), a trailing "or better" plus (99+%, 99 +%, 99.9 +%), and whitespace before the %.

      Parameters

      • value: string

        The string to extract the purity from

      Returns number | void

      The purity as a number (e.g. 95), or nothing if none is found

      parsePurity("Sodium borohydride, min 95%")   // Returns 95
      parsePurity("Hydroquinone ≥99.8%, extra pure") // Returns 99.8
      parsePurity("Lithium Carbonate 99+% Extra Pure") // Returns 99
      parsePurity("Potassium hydrogen tartrate ≥99,5 %") // Returns 99.5
      parsePurity("Sodium carbonate 99.7 +%, pure") // Returns 99.7
      parsePurity("120%") // Returns nothing (out of range)
      parsePurity("no percentage here") // Returns nothing
      export const parsePurity = (value: string): number | void => {
      if (!value || typeof value !== 'string') return;

      // Number (dot or comma decimal), an optional trailing "+" (with optional
      // spaces), then "%". Anchoring on "%" keeps stray digits (codes like "E515")
      // from being read as a purity.
      const match = value.match(/(\d+(?:[.,]\d+)?)\s*\+?\s*%/);
      if (!match) return;

      const purity = Number(match[1].replace(',', '.'));
      if (!Number.isNaN(purity) && purity > 0 && purity <= 100) return purity;
      };