Escape LaTeX Special Characters

1.2.0 · active · verified Sun Apr 19

escape-latex is a JavaScript utility for sanitizing strings by escaping LaTeX special characters, making them safe for inclusion in LaTeX documents. The current stable version is 1.2.0. As a focused utility, it typically has an infrequent release cadence, with updates primarily for bug fixes or minor enhancements. Its key differentiators include the ability to selectively escape characters that would simply malform LaTeX (`# $ % & \ ^ _ { }`) versus those that affect formatting (spaces, en-dashes, em-dashes) via the `preserveFormatting` option. Furthermore, it provides an `escapeMapFn` callback, allowing developers to fully customize or extend the character-to-escape mapping based on specific LaTeX requirements, offering flexibility beyond standard escaping mechanisms. It is designed for use in Node.js environments.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic, formatting-preserving, and custom character escaping using `escape-latex` in an ESM context.

import lescape from 'escape-latex';

// Basic escaping: only characters that would malform LaTeX are escaped.
// Note: multiple spaces might be collapsed by LaTeX.
const basicEscaped = lescape("Hello #World! This is $money & more.");
console.log('Basic Escaped:', basicEscaped);

// Preserving formatting: also escapes spaces, tabs, en-dashes, em-dashes.
// LaTeX will render multiple spaces as multiple non-breaking spaces.
const formattedEscaped = lescape("Hello   World -- with dashes --- and tabs\t!", { preserveFormatting: true });
console.log('Formatted Escaped:', formattedEscaped);

// Custom escaping: use escapeMapFn to define specific character mappings.
const customEscaped = lescape("Custom! @ symbol.", {
  escapeMapFn: (defaultEscapes, formattingEscapes) => {
    // Add an escape for '@' symbol
    defaultEscapes['@'] = '\\at{}'; 
    return Object.assign({}, defaultEscapes, formattingEscapes);
  }
});
console.log('Custom Escaped:', customEscaped);

/*
Example Output:
Basic Escaped: Hello \#World! This is \$money \& more.
Formatted Escaped: Hello~~~World~--~with~dashes~---~and~tabs\\t!
Custom Escaped: Custom! \at{} symbol.
*/

view raw JSON →