A robust JavaScript utility that converts LaTeX mathematical expressions into Math.js compatible syntax. This converter handles a wide range of mathematical notation including fractions, roots, trigonometric functions, logarithms, and complex nested expressions.
- Features
- Installation
- Usage
- Supported LaTeX Commands
- How It Works
- Examples
- Contributing
- License
- Star the Repository
- Comprehensive LaTeX Support: Handles fractions, roots, exponents, trigonometric functions, logarithms, and more
- Nested Expression Handling: Properly processes deeply nested mathematical expressions
- Implicit Multiplication: Automatically adds multiplication operators where needed (e.g.,
2x→2*x) - Smart Function Recognition: Distinguishes between mathematical functions and variable names
- Absolute Value Support: Converts both
\left| \right|and simple| |notation - Reciprocal Trig Functions: Handles
\sec,\csc,\cotby converting to their reciprocal forms
Simply import the function into your JavaScript project:
import { latexToMathJs } from './LatexToMathJs.js';Or if using CommonJS:
const { latexToMathJs } = require('./LatexToMathJs.js');import { latexToMathJs } from './LatexToMathJs.js';
// Basic usage
const latex = '\\frac{x^2 + 1}{2}';
const mathJs = latexToMathJs(latex);
console.log(mathJs); // Output: ((x^(2))+1)/(2))
// With Math.js evaluation
import { evaluate } from 'mathjs';
const result = evaluate(mathJs, { x: 3 });
console.log(result); // Output: 5\frac{numerator}{denominator}→((numerator)/(denominator))
\sqrt{x}→sqrt(x)\sqrt[n]{x}→(x^(1/n))
- Standard:
\sin,\cos,\tan - Inverse:
\arcsin,\arccos,\arctan,\sin^{-1},\cos^{-1},\tan^{-1} - Reciprocal:
\sec,\csc,\cot(converted to1/cos,1/sin,1/tan)
\ln{x}→log(x)(natural logarithm)\log{x}→log10(x)(base 10)
\exp{x}→exp(x)e^{x}→exp(x)x^{n}→(x^(n))x^2→(x^2)
\left| x \right|→abs(x)|x|→abs(x)
\pi→pi\e→e\infty→Infinity
\cdot→*\times→*\div→/\pm→+(plus-minus treated as plus)
\left(,\right),\left[,\right],\left\{,\right\}→()
The converter processes LaTeX expressions through several carefully ordered stages:
// Handles \left| ... \right| and | ... |
expr = expr.replace(/\\left\|([^|]+)\\right\|/g, 'abs($1)');Absolute values are processed first to prevent interference with other operators.
// Recursively handles nested fractions
do {
prevExpr = expr;
expr = expr.replace(/\\frac\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}/g,
'(($1)/($2))');
} while (expr !== prevExpr);Uses a loop to handle deeply nested fractions like \frac{\frac{a}{b}}{c}.
// nth roots and square roots
expr = expr.replace(/\\sqrt\[([^\]]+)\]\{([^}]+)\}/g, '(($2)^(1/($1)))');
expr = expr.replace(/\\sqrt\{([^}]+)\}/g, '(sqrt($1))');Inverse functions are processed before regular ones to prevent incorrect conversions:
// Inverse trig first
expr = expr.replace(/\\arctan/g, 'atan');
// Then regular trig
expr = expr.replace(/\\tan/g, 'tan');Handles functions with explicit arguments and space-separated notation:
// sin x → sin(x)
expr = expr.replace(/sin\s+([a-zA-Z])/g, 'sin($1)');// Special case: e^{...} → exp(...)
expr = expr.replace(/e\^\{([^}]+)\}/g, 'exp($1)');
// General powers: x^{n} → (x^(n))
expr = expr.replace(/([a-zA-Z0-9]+)\^\{([^}]+)\}/g, '($1^($2))');This is the most complex part, using a state machine approach:
const knownFuncs = ['sin', 'cos', 'tan', 'asin', 'acos', 'atan', ...];
while (i < expr.length) {
// Check if current position starts a known function
if (matchedFunc) {
// Don't add multiplication within function names
} else if (isVariable) {
// Add * between consecutive variables (xy → x*y)
// But NOT between variable and function (xsin → x*sin, not xs*in)
}
}The algorithm handles:
- Number + variable:
2x→2*x - Variable + variable:
xy→x*y(but preserves function names likesin) - Number + parenthesis:
2(x)→2*(x) - Closing + opening parens:
)(→)*( - Variable + parenthesis:
x(y)→x*(y)(except for functions)
Final step removes remaining LaTeX backslashes and extra spaces.
latexToMathJs('x^2 + 2x + 1');
// Output: (x^2)+2*x+1
latexToMathJs('\\frac{1}{2}x');
// Output: ((1)/(2))*xlatexToMathJs('\\sin(x) + \\cos(x)');
// Output: sin(x)+cos(x)
latexToMathJs('\\sec(x)');
// Output: (1/cos(x))
latexToMathJs('\\arctan(y)');
// Output: atan(y)latexToMathJs('\\frac{\\sin(x)}{\\cos(x)}');
// Output: ((sin(x))/(cos(x)))
latexToMathJs('\\sqrt{\\frac{a^2 + b^2}{c}}');
// Output: (sqrt(((a^(2))+(b^(2)))/(c)))
latexToMathJs('e^{-\\frac{x^2}{2}}');
// Output: exp(-((x^(2))/(2)))latexToMathJs('\\left| x - 1 \\right|');
// Output: abs(x-1)
latexToMathJs('|x| + |y|');
// Output: abs(x)+abs(y)latexToMathJs('2xy');
// Output: 2*x*y
latexToMathJs('(x+1)(x-1)');
// Output: (x+1)*(x-1)
latexToMathJs('\\pi r^2');
// Output: pi*r^(2)We welcome contributions! If you find any bugs or have suggestions for improvements, please:
- Check existing issues to avoid duplicates
- Create a new issue with:
- Clear description of the bug
- Input LaTeX expression
- Expected output
- Actual output
- Steps to reproduce
- Fork the repository
- Create a new branch (
git checkout -b feature/your-feature-name) - Make your changes
- Add tests if applicable
- Commit your changes (
git commit -m 'Add some feature') - Push to the branch (
git push origin feature/your-feature-name) - Open a Pull Request
- Maintain the existing code style
- Add comments for complex logic
- Update the README if adding new features
- Test with various LaTeX expressions
- Additional LaTeX command support
- Performance optimizations
- Better error handling
- More comprehensive test coverage
- Documentation improvements
If you find this project useful, please consider giving it a star on GitHub! It helps others discover the project and motivates continued development.
- Math.js - Extensive math library for JavaScript
- KaTeX - Fast math typesetting library
- MathJax - Beautiful math in all browsers
If you need help or have questions:
- Open an issue on GitHub
- Check existing documentation
- Review the examples above
Made with ❤️ for the mathematical community