Writing code

FUNCTION

toRegExpLiteral

@skmtc/lang-typescript 0.19.1

A pattern as a regex literal in generated code: /source/flags.

The JavaScript engine writes the literal. new RegExp(source, flags) checks the pattern and the flags, and its toString() escapes only what would break the literal: a / outside a character class, and a line terminator (\n, \r, \u2028, \u2029). An empty pattern renders as /(?:)/, since // starts a comment. So the literal parses wherever the pattern does, and it matches what the pattern matches.

The check is the generator's own JavaScript engine. Syntax newer than the consumer's engine or TypeScript target, such as (?i:a) modifiers or duplicate named groups, passes here and then fails to parse in the generated file.

Throws a SyntaxError when the pattern or the flags are not valid JavaScript: a trailing \, which would escape the closing /; a leading *, which would open a block comment; a pattern written for another engine ((?i)); or flags such as 'gg', 'uv' or 'g;run()//'. A generator that reads pattern from a schema catches it and leaves that pattern out, or lets that one item fail.

Signature

import { toRegExpLiteral } from '@skmtc/lang-typescript'

toRegExpLiteral(source: string, flags?: string): string

Parameters

source, string required
flags, string
Example
toRegExpLiteral('^a/b$')        // '/^a\\/b$/'
toRegExpLiteral('^[/]$')        // '/^[/]$/'
toRegExpLiteral('^x-', 'u')     // '/^x-/u'
toRegExpLiteral('')             // '/(?:)/'
toRegExpLiteral('*x')           // throws SyntaxError

Returns

string