Skip to main content

escape

A function that escapes a string for use in a regular expression.

The returned string is suitable for use when building dynamic regular expressions that should match the original string exactly.

caution

The escaped string is suitable only for use in matching literal strings. In other words, it is not suitable for escaping characters inside regular expression character classes.

Parameters

escape accepts a single string parameter.

Return value

escape will return an escaped version of the original string.

Usage

import { escape } from "@snout/regexp";

const happyFace = new RegExp(escape("^_^"));

happyFace.test("^_^"); // returns true
happyFace.test("-_-"); // returns false
import { escape } from "@snout/regexp";

function trimSuffix(suffix: string, value: string): string {
return value.replace(new RegExp(`${escape(suffix)}$`), "");
}

trimSuffix("()", "functionName()"); // returns "functionName"