Escape String RegExp is a lightweight JavaScript utility that escapes RegExp special characters in strings, making them safe to use as literal text within regular expressions. It provides Unicode-safe escaping to prevent regex injection vulnerabilities when constructing regular expressions from user input or dynamic content.
npm install escape-string-regexpimport escapeStringRegexp from 'escape-string-regexp';TypeScript:
import escapeStringRegexp from 'escape-string-regexp';import escapeStringRegexp from 'escape-string-regexp';
// Escape a string for safe use in RegExp
const userInput = 'How much $ for a 🦄?';
const escapedString = escapeStringRegexp(userInput);
console.log(escapedString);
//=> 'How much \\$ for a 🦄\\?'
// Use the escaped string in a regular expression
const regex = new RegExp(escapedString);
console.log(regex.test(userInput)); // true
// Common use case: search for literal text in a larger string
const searchFor = '$.99';
const text = 'The price is $.99 today';
const searchRegex = new RegExp(escapeStringRegexp(searchFor), 'g');
console.log(text.match(searchRegex)); // ['$.99']Escapes all RegExp special characters in a string to make it safe for literal use in regular expressions.
/**
* Escape RegExp special characters in a string
* @param string - The input string to escape
* @returns The escaped string with special RegExp characters properly escaped
* @throws TypeError when input is not a string
*/
function escapeStringRegexp(string: string): string;Escaped Characters:
|, \, {, }, (, ), [, ], ^, $, +, *, ?, .- (escaped as \x2d for Unicode pattern compatibility)Error Handling:
TypeError with message "Expected a string" when input is not a stringUsage Examples:
// Basic escaping of special characters
escapeStringRegexp('hello.world');
//=> 'hello\\.world'
escapeStringRegexp('user@domain.com');
//=> 'user@domain\\.com'
// Escaping complex patterns
escapeStringRegexp('[urgent] $100+ required');
//=> '\\[urgent\\] \\$100\\+ required'
// Unicode-safe dash escaping
escapeStringRegexp('foo-bar');
//=> 'foo\\x2dbar'
// Error handling
try {
escapeStringRegexp(123);
} catch (error) {
console.log(error.message); // "Expected a string"
}
// Common pattern: case-insensitive search
const searchTerm = 'Mr. Smith';
const text = 'Looking for mr. smith in the database';
const regex = new RegExp(escapeStringRegexp(searchTerm), 'i');
console.log(regex.test(text)); // trueImplementation Details:
\\$&) for most special RegExp characters\\x2d) for dash character to ensure compatibility with Unicode flagSecurity Considerations: