js-tokens

10.0.0 · active · verified Sun Apr 19

js-tokens is a JavaScript tokenizer that leverages regular expressions to parse JavaScript code into a stream of tokens. It is known for its tiny footprint, lenient parsing approach, and robustness, designed to 'never fail' even on malformed input, making it suitable for tools that need to process potentially incomplete or invalid JavaScript. The current stable version is 10.0.0. While not strictly spec-compliant in all edge cases, its 'almost spec-compliant' nature makes it highly practical for tasks like syntax highlighting, basic static analysis, or code transformation where full AST parsing is overkill. It supports the latest ECMAScript features up to ES2025 and also offers an option for JSX support. The project maintains a steady release cadence for new ECMAScript features and bug fixes, with major versions often introducing changes to module formats or API surface to align with ecosystem shifts.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic tokenization of a JavaScript string, extracting token values. Also shows enabling JSX support.

import jsTokens from 'js-tokens';

const jsString = 'JSON.stringify({k:3.14**2}, null /*replacer*/, "\t")';

const tokens = Array.from(jsTokens(jsString));

console.log(tokens.map(token => token.value).join('|'));
// Expected output: JSON|.|stringify|(|{|k|:|3.14|**|2|}|,| |null| |/*replacer*/|,| |"\t"|)

// Example with JSX support
const jsxString = 'const element = <div>Hello, {name}!</div>;';
const jsxTokens = Array.from(jsTokens(jsxString, { jsx: true }));
console.log(jsxTokens.map(token => token.type + ':' + token.value).join(', '));

view raw JSON →