This utility provides a robust way to find and render LaTeX mathematical expressions embedded within a larger text string using the KaTeX library. It intelligently handles various delimiters, escaped characters, and overlaps.
- Renders LaTeX to HTML: Uses the KaTeX library for fast and accurate math rendering.
- Multiple Delimiter Support: Recognizes common inline (
$...$,\(...\)) and display ($$...$$,\[...\],\begin{align}...,\begin{align*}...) math delimiters. - Escaped Character Handling: Correctly interprets escaped delimiters (e.g.,
\$) and backslashes (\\) within both text and math contexts. - Overlap Prevention: Prioritizes delimiter matches to prevent issues where delimiters might overlap.
- Segmented Processing: Parses the input into distinct 'text' and 'math' segments for accurate rendering.
- COMING SOON: Configurable Delimiters: The set of delimiters can be configured within the code.
Install the package using npm or yarn:
npm install render-latex
# or
yarn add render-latexYou also must include the KaTeX CSS stylesheet in your project for the math to render correctly. Add the following to the <head> of your HTML:
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.22/dist/katex.min.css" integrity="sha384-5TcZemv2l/9On385z///+d7MSYlvIEw9FuZTIdZ14vJLqWphw7e7ZPuOiCHJcFCP" crossorigin="anonymous">Import the renderMath function from the package and pass it the string you want to process. Remember to include the KaTeX CSS.
import { renderMath } from 'render-latex';
const inputText = `
This is a paragraph with inline math like $E=mc^2$.
$$
\\int_0^\\infty e^{-x^2} dx = \\frac{\\sqrt{\\pi}}{2}
$$
More text after math.
`;
const renderedHtml = renderMath(inputText);
console.log(renderedHtml);- Escaping: The input string first has potentially problematic sequences like
\\and\$replaced with unique placeholder characters. This prevents them from being misinterpreted as delimiters or LaTeX commands during parsing. - Delimiter Parsing (
parseDelimiters):- The code iterates through a predefined list of delimiters (
$,$$,\(,\[,\begin{align*}, etc.). - For each delimiter, it uses regular expressions to find all occurrences in the escaped input string.
- It keeps track of character indices that have already been matched to prevent processing overlapping delimiters (e.g., it won't process
$b$inside$$a $b$ c$$separately if$$...$$is found first). - The string is segmented into an ordered array of objects, each marked as either
textormath, along with its content and whether display mode should be used for math.
- The code iterates through a predefined list of delimiters (
- Rendering (
renderMath):- The function iterates through the parsed segments.
- Text Segments: Placeholder characters are reverted to their original form (
\and$). The text is appended to the output. - Math Segments: Placeholder characters are reverted to their LaTeX-compatible forms (
\\and$). The content is then rendered usingkatex.renderToStringwith appropriate options (displayMode, error handling disabled).
- Output: The final result is a string containing the original text interleaved with HTML generated by KaTeX for the math segments.
The following delimiters are configured by default:
| Start | End | Type |
|---|---|---|
$$ |
$$ |
display |
$ |
$ |
inline |
\[ |
\] |
display |
\( |
\) |
inline |
\begin{align*} |
\end{align*} |
display |
\begin{align} |
\end{align} |
display |
The following options are passed to katex.renderToString internally:
displayMode: Set totruefor display math,falsefor inline math.throwOnError: false: Prevents KaTeX from throwing errors on invalid syntax, rendering an error message instead.strict: false: Disables strict mode, allowing some non-standard LaTeX commands.trust: true: Allows certain commands like\htmlClass