Character Parser for Template Snippets

4.0.0 · active · verified Sun Apr 19

`character-parser` is a focused JavaScript utility library designed for parsing JavaScript code snippets, particularly within template languages like EJS or Jade. Its primary function is to robustly handle bracket nesting, strings, and comments, allowing for the reliable extraction of delimited JavaScript sections without performing a full syntax validation or abstract syntax tree (AST) generation. The current stable version is 4.0.0, which introduced significant changes including native ES module support and updated package export configurations. This library differentiates itself by offering a lightweight, character-by-character parsing mechanism and state management, providing functions to parse entire strings or single characters, track nesting depth, and find code segments based on custom delimiters while intelligently ignoring content within nested structures or comments. It does not aim to be a comprehensive JavaScript parser but rather a precise tool for template-driven code extraction.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `character-parser` to find delimited expressions and manage parsing state across multiple string segments, including handling nested structures and escaped characters.

import { parseUntil, parse } from 'character-parser';
import assert from 'assert';

console.log('--- Custom Delimited Expressions (EJS-style) ---');
// Example 1: Parsing up to a custom delimiter (EJS-style)
const ejsSnippet = 'foo.bar("%>\").baz%> bing bong';
const section1 = parseUntil(ejsSnippet, '%>');
assert.strictEqual(section1.start, 0);
assert.strictEqual(section1.end, 18);
assert.strictEqual(section1.src, 'foo.bar("%>\").baz');
console.log(`Parsed section 1: "${section1.src}" (Start: ${section1.start}, End: ${section1.end})`);

const ejsSnippetOffset = '<%foo.bar("%>\").baz%> bing bong';
const section2 = parseUntil(ejsSnippetOffset, '%>', { start: 2 });
assert.strictEqual(section2.start, 2);
assert.strictEqual(section2.end, 20);
assert.strictEqual(section2.src, 'foo.bar("%>\").baz');
console.log(`Parsed section 2 with offset: "${section2.src}" (Start: ${section2.start}, End: ${section2.end})`);

console.log('\n--- Parsing Depth Changes ---');
// Example 2: Parsing depth changes with state management
let state = parse('foo(arg1, arg2, {\n  foo: [a, b\n');
console.log('Initial stack after first parse:', state.stack);
assert.deepStrictEqual(state.stack, [')', '}', ']']);

state = parse('    c, d]\n  })', state);
console.log('Final stack after second parse:', state.stack);
assert.deepStrictEqual(state.stack, []);

console.log('\nAll assertions passed!');

view raw JSON →