React Input That Calculates Arithmetic Expressions Without eval
If you type "1200*3+500" into an amount field, "= 4,100" appears just below it. Press Enter and the field's contents are replaced with "4100". The calculation doesn't use eval. I wrote a TypeScript function that only reads addition, subtraction, multiplication, division, and parentheses. It also works on pages that set a Content-Security-Policy (CSP) forbidding eval.
Test environment: Ubuntu 24.04, Node.js 22.23.4, Chromium 153. I used react / react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx file with tsc, transformed it with esbuild, and operated a development build wrapped in StrictMode with Playwright. Full-width characters were entered with Playwright's insertText. I did not test actual Japanese IME input. I did not test Firefox, Safari, smartphones, or screen reader announcements.

Why not eval
JavaScript has eval(), which runs a string as code. In the Chromium used for testing, eval('1200*3+500') returned 4100. However, MDN's eval() page has a section warning against direct use of eval(), which explains that if a malicious string is passed in, the code runs with the page's privileges. Users can type anything into the input, so I avoid passing that text to eval.
The other reason is CSP. According to MDN's script-src explanation, on pages where script-src doesn't include 'unsafe-eval', eval() and the Function() constructor are blocked. In testing, I served the page with Content-Security-Policy: script-src 'self'. In Chromium, both eval('1200*3+500') and new Function('return 1200*3+500')() threw EvalError. On the same page, typing "1200*3+500" into this article's input and pressing Enter changed the field to "4100".
The function that reads expressions
The calculation logic is in calc.ts. It works in two stages: tokenize, which splits the string into numbers and operators, and parse, which reads that sequence and calculates the result.
// Reads an arithmetic expression and calculates it (without eval)
export type CalcResult =
| { kind: 'empty' }
| { kind: 'ok'; value: number }
// incomplete: an error that may go away if you keep typing (e.g. "1+", "(2", "5/0")
| { kind: 'error'; message: string; incomplete: boolean };
type Token =
| { type: 'num'; value: number; pos: number }
| { type: 'op'; value: '+' | '-' | '*' | '/' | '(' | ')'; pos: number };
const INCOMPLETE = '式が途中で終わっています';
const NO_CLOSE = '「)」が足りません';
const DIV_ZERO = '0で割ることはできません';
// Message for when the value goes beyond the range Number can represent exactly (±9007199254740991)
const TOO_LARGE = '大きすぎて正確に計算できません';
// Converts full-width digits and symbols, and ×÷, to half-width symbols
export function normalize(text: string): string {
return text
.normalize('NFKC')
.replace(/×/g, '*')
.replace(/÷/g, '/')
.replace(/−/g, '-');
}
// Splits the expression string into numbers and symbols
function tokenize(s: string): Token[] {
const tokens: Token[] = [];
// Text of the number just read (empty unless right after a number)
let lastNum = '';
let i = 0;
while (i < s.length) {
const c = s[i];
if (/\s/.test(c)) {
lastNum = '';
i++;
continue;
}
if ('+-*/()'.includes(c)) {
tokens.push({ type: 'op', value: c as '+', pos: i });
lastNum = '';
i++;
continue;
}
// Number: accepts comma thousands separators like 1,200, and decimal points
const m = /^(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?|^\.\d+/.exec(s.slice(i));
if (m) {
const value = Number(m[0].replace(/,/g, ''));
if (value > Number.MAX_SAFE_INTEGER) throw new Error(TOO_LARGE);
tokens.push({ type: 'num', value, pos: i });
lastNum = m[0];
i += m[0].length;
continue;
}
// The expression ends while a number is still being typed, like "1200." or "1,20"
const rest = s.slice(i);
if (!lastNum.includes('.')) {
if (rest === '.') throw new Error(INCOMPLETE);
if (/^,\d{0,2}$/.test(rest) && /^\d{1,3}(?:,\d{3})*$/.test(lastNum)) throw new Error(INCOMPLETE);
}
throw new Error(`${i + 1}文字目の「${c}」は使えません`);
}
return tokens;
}
// Three-level functions so that multiplication and division are calculated first
// expr = term (('+' | '-') term)*
// term = factor (('*' | '/') factor)*
// factor = ('+' | '-') factor | num | '(' expr ')'
function parse(tokens: Token[]): number {
// Checks that intermediate results also stay within the exactly representable range
const safe = (v: number) => {
if (!(Math.abs(v) <= Number.MAX_SAFE_INTEGER)) throw new Error(TOO_LARGE);
return v;
};
let i = 0;
const peek = () => tokens[i];
function expr(): number {
let v = term();
for (let t = peek(); t?.type === 'op' && (t.value === '+' || t.value === '-'); t = peek()) {
i++;
const r = term();
v = safe(t.value === '+' ? v + r : v - r);
}
return v;
}
function term(): number {
let v = factor();
for (let t = peek(); t?.type === 'op' && (t.value === '*' || t.value === '/'); t = peek()) {
i++;
const r = factor();
if (t.value === '/' && r === 0) throw new Error(DIV_ZERO);
v = safe(t.value === '*' ? v * r : v / r);
}
return v;
}
function factor(): number {
const t = peek();
if (!t) throw new Error(INCOMPLETE);
i++;
if (t.type === 'num') return t.value;
if (t.value === '-') return -factor();
if (t.value === '+') return factor();
if (t.value === '(') {
const v = expr();
if (peek()?.value !== ')') throw new Error(NO_CLOSE);
i++;
return v;
}
throw new Error(`${t.pos + 1}文字目の「${t.value}」の位置がおかしいです`);
}
const v = expr();
const rest = peek();
if (rest) throw new Error(`${rest.pos + 1}文字目の「${rest.value}」の位置がおかしいです`);
return v;
}
export function calculate(text: string): CalcResult {
const s = normalize(text);
if (s.trim() === '') return { kind: 'empty' };
try {
const value = parse(tokenize(s));
// Round errors like 0.1 + 0.2 = 0.30000000000000004 to 15 significant digits
return { kind: 'ok', value: Number.isInteger(value) ? value : Number(value.toPrecision(15)) };
} catch (e) {
const message = (e as Error).message;
return { kind: 'error', message, incomplete: [INCOMPLETE, NO_CLOSE, DIV_ZERO].includes(message) };
}
}
Multiplication and division first
The three functions expr, term, and factor inside parse determine the order of calculation. expr reads the parts joined by "+" and "-", and term reads the parts joined by "" and "/". expr has term read the operands for adding or subtracting, so for "1+23", term first turns "2*3" into 6, and then it's added to 1 to get 7.
Parentheses are read by factor. When "(" comes, it calls expr again and returns the contents of the parentheses as a single number. A "-" before a number is also read by factor, so "2*-3" and "-(2+3)*4" can be calculated. Here are the results from testing with Node.js.
| Expression | Result |
|---|---|
| 1+2*3 | 7 |
| (1+2)*3 | 9 |
| 10-2-3 | 5 |
| 100/4/5 | 5 |
| 2*-3 | -6 |
| -(2+3)*4 | -20 |
| 1,200*1.1 | 1320 |
10-2-3 gives 5 because the for loop calculates from left to right. Numbers with thousands separators such as "1,200" are read correctly. When the input ends in the middle of a number, as in "1200." or "1,20", it is treated as an incomplete expression, with the message 式が途中で終わっています (the expression ends prematurely).
Full-width digits and symbols, and × and ÷
In the custom normalize function, NFKC normalization is applied first using the normalize() method of strings. This converts full-width digits and the full-width +, -, *, /, (, and ) to half-width. On the other hand, "×", "÷", and the mathematical minus sign "−" (U+2212) did not change under NFKC, so they are replaced with replace.
As a result, "1200×3+500" gives 4100, and "(1+2)÷3" gives 1.
Round decimal errors to 15 significant digits
As MDN's Number page explains, JavaScript numbers are IEEE 754 double-precision binary floating-point values, so precision is limited. In the test environment, 0.1 + 0.2 gave 0.30000000000000004, 0.1 * 3 gave 0.30000000000000004, and 1.1 * 1.1 gave 1.2100000000000002. If these were shown in the input as-is, users would see them as mistakes.
So for non-integer results, I convert the value to a string with 15 significant digits using toPrecision(15), then convert it back to a number with Number. This makes 0.1+0.2 give 0.3 and 1.1*1.1 give 1.21. 1/3 gives 0.333333333333333, with fifteen 3s.
Integer results are not rounded. If integers also went through toPrecision(15), the 16-digit 1234567890123457 would become 1234567890123460, with the last digit changed to 0. With the current approach, which doesn't round integers, "1234567890123456+1" gives 1234567890123457.
Numbers that are too large produce an error. As the Number.MAX_SAFE_INTEGER documentation explains, the integers JavaScript can represent exactly are ±(253 − 1), that is, up to ±9007199254740991. If a number in the expression or any intermediate result exceeds this, the function returns 大きすぎて正確に計算できません (too large to calculate accurately). "9007199254740991+1" and "3000000000*3000000000" produced this error. "9007199254740991+2-2" also produced it, even though its final result is within the range.
Unreadable expressions return an error message showing the problem
For expressions that can't be read, the code throws an exception, and calculate catches it and returns an error message.
| Expression | Error message |
|---|---|
| 1+ | 式が途中で終わっています (the expression ends prematurely) |
| (1+2 | 「)」が足りません (a closing parenthesis is missing) |
| 1+*2 | 3文字目の「*」の位置がおかしいです (the "*" at character 3 is in the wrong place) |
| 1+2) | 4文字目の「)」の位置がおかしいです (the ")" at character 4 is in the wrong place) |
| 2^3 | 2文字目の「^」は使えません (the "^" at character 2 can't be used) |
| 1e3 | 2文字目の「e」は使えません (the "e" at character 2 can't be used) |
| 1/0, 5/(2-2) | 0で割ることはできません (cannot divide by zero) |
In JavaScript, 1 / 0 gives Infinity, but returning "Infinity" to the input makes no sense, so division by zero is treated as an error. Exponent notation such as "1e3" and exponentiation with "^" are outside the four operations, so they are not read.
The input component
import { useId, useState } from 'react';
import { calculate } from './calc';
const format = new Intl.NumberFormat('ja-JP', { maximumFractionDigits: 15 });
type Props = {
label: string;
initial?: string;
// Called when committed with a calculation result
onCommit?: (value: number) => void;
};
export function CalcInput({ label, initial = '', onCommit }: Props) {
const id = useId();
const [text, setText] = useState(initial);
// Set to true when Enter or blur happens and the calculation failed
const [tried, setTried] = useState(false);
const result = calculate(text);
// Errors that may go away if you keep typing are not shown until a commit is attempted
const error = result.kind === 'error' && (tried || !result.incomplete) ? result.message : '';
// Replaces the expression with the calculation result
function commit() {
if (result.kind !== 'ok') {
setTried(result.kind === 'error');
return;
}
setText(String(result.value));
onCommit?.(result.value);
}
return (
<div className="calc">
<label htmlFor={id}>{label}</label>
<input
id={id}
autoComplete="off"
value={text}
aria-invalid={error !== ''}
aria-describedby={`${id}-msg`}
onChange={(e) => {
setText(e.target.value);
setTried(false);
}}
onKeyDown={(e) => {
// Don't calculate on the Enter that confirms a Japanese IME conversion
if (e.key !== 'Enter' || e.nativeEvent.isComposing) return;
// Don't submit the form when replacing an expression with its result, or on error
const settled = result.kind === 'empty' || (result.kind === 'ok' && String(result.value) === text);
if (!settled) e.preventDefault();
commit();
}}
onBlur={commit}
/>
<p id={`${id}-msg`} className={error ? 'error' : 'preview'}>
{error || (result.kind === 'ok' ? `= ${format.format(result.value)}` : '')}
</p>
</div>
);
}
.calc {
display: grid;
gap: 4px;
max-width: 320px;
}
.calc input {
font-size: 1.125rem;
padding: 6px 8px;
}
.calc p {
min-height: 1.5em;
margin: 0;
}
.calc .preview {
color: #067a98;
}
.calc .error {
color: #d85878;
}
The state holds two things: the input string text, and tried, which records whether a commit attempt failed. The calculation result is not kept in state. It is computed from text on every render. I kept the input as type="text". In Chromium, typing "1200*3+500" into a type="number" field made value an empty string, so the expression couldn't be read.
Don't show errors while typing
If you type "12003+500" one character at a time, the expression is incomplete at "1200" and at "1200*3+". Showing an error at every keystroke would make the display flash red and clear again each time.
So calculate returns incomplete: true for errors that could be fixed by continuing to type. There are three kinds: the expression ends prematurely, a closing parenthesis is missing, or the code divides by zero. Division by zero is included because after "5/0", typing ".5" makes a valid expression. In the component, these errors are not shown until tried becomes true. The downside is that a division by zero that typing won't fix, like "10/(5-5)", also shows no error until a commit is attempted.
Here is what appeared when I typed one character at a time in Chromium. While the expression could still be fixed by typing more, the display below the input is empty.
| Typed expression | Display after each keystroke |
|---|---|
| 1200*3+500 | = 1, = 12, = 120, = 1,200, (empty), = 3,600, (empty), = 3,605, = 3,650, = 4,100 |
| 1200.5 | = 1, = 12, = 120, = 1,200, (empty), = 1,200.5 |
| 5/0.5 | = 5, (empty), (empty), (empty), = 10 |
Errors that typing won't fix, like "2^" or "1.5.", show the error message as soon as they are typed, and set aria-invalid on the input to true.
Commit on Enter and on blur
commit replaces the input's string with the result when the calculation succeeds, and passes the number to the parent through onCommit. It's called when Enter is pressed and when the field loses focus (onBlur). In Chromium, pressing Enter with "1200*3+500" changed the field to "4100". Typing full-width "1200×3" and moving focus away with the Tab key changed it to "3600".
If you press Enter on an incomplete expression like "1+", the field stays "1+" and shows 式が途中で終わっています. Typing "2" next calls onChange, which resets tried to false, so the error message disappears and changes to "= 3".
An expression that divides by zero, such as "(1200+800)/(3-3)", shows nothing right after typing. Pressing Enter shows 0で割ることはできません (cannot divide by zero).

When the input is inside a <form>, Enter submits the form. When the expression is being replaced with its result, or when there's an error, the code calls preventDefault() to stop the submission. In testing, pressing Enter with "12003+500" or "1+" did not submit the form. When the field contains only a number, like "4100", or is empty, the code doesn't block the event, so Enter submits as usual. After typing "12003+500" and pressing Enter twice, the first press replaced the expression with "4100", and the second press submitted the form. Pressing Enter in a number-only field calls onCommit again with the same value.
For the Enter check, when e.nativeEvent.isComposing is true, nothing happens. According to MDN's isComposing explanation, this property indicates whether a keyboard event occurred during input method composition, such as Japanese IME conversion (after compositionstart and before compositionend). This check keeps the Enter that confirms a conversion from also triggering the calculation.
After a commit, the expression disappears and only the resulting number remains in the field. The expression can't be reviewed afterward, so this approach doesn't suit fields where the expression itself needs to be kept.





