Escapes RegExp special characters in strings for safe dynamic regular expression construction.
npx @tessl/cli install tessl/npm-lodash--escaperegexp@4.1.0Escapes RegExp special characters in strings, enabling safe use of user input or dynamic content within regular expressions. This modular export from the lodash library allows you to include only the escapeRegExp functionality without the entire lodash dependency.
npm install lodash.escaperegexpconst escapeRegExp = require('lodash.escaperegexp');const escapeRegExp = require('lodash.escaperegexp');
// Escape special characters for safe RegExp construction
const userInput = '[lodash](https://lodash.com/)';
const escaped = escapeRegExp(userInput);
console.log(escaped);
// => '\\[lodash\\]\\(https://lodash\\.com/\\)'
// Use escaped string in RegExp
const regex = new RegExp(escaped);
const text = 'Check out [lodash](https://lodash.com/) for utilities!';
console.log(regex.test(text)); // => true
// Safe search and replace
const searchTerm = '*.js';
const escapedTerm = escapeRegExp(searchTerm);
const pattern = new RegExp(escapedTerm, 'g');
const filename = 'my-script*.js matches *.js pattern';
console.log(filename.replace(pattern, 'REDACTED'));
// => 'my-script REDACTED matches REDACTED pattern'Escapes all RegExp special characters in a string for safe dynamic regular expression construction.
/**
* Escapes the RegExp special characters "^", "$", "\\", ".", "*", "+",
* "?", "(", ")", "[", "]", "{", "}", and "|" in string.
*
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
*/
function escapeRegExp(string)Parameters:
string (string, optional): The string to escape. Defaults to empty string if not provided.Returns:
Special Character Handling: The function escapes these RegExp special characters:
^ → \\^ (caret)$ → \\$ (dollar)\\ → \\\\ (backslash). → \\. (dot)* → \\* (asterisk)+ → \\+ (plus)? → \\? (question mark)( → \\( (left parenthesis)) → \\) (right parenthesis)[ → \\[ (left square bracket)] → \\] (right square bracket){ → \\{ (left curly brace)} → \\} (right curly brace)| → \\| (pipe)Type Handling:
Usage Examples:
// Basic escaping
escapeRegExp('hello.world');
// => 'hello\\.world'
// Multiple special characters
escapeRegExp('(test)*+?');
// => '\\(test\\)\\*\\+\\?'
// Null/undefined handling
escapeRegExp(null);
// => ''
escapeRegExp(undefined);
// => ''
// Empty string
escapeRegExp('');
// => ''
// Numbers
escapeRegExp(123);
// => '123'
// Preserves -0 sign
escapeRegExp(-0);
// => '-0'
// Complex patterns
escapeRegExp('[a-z]+\\.(js|ts)$');
// => '\\[a-z\\]\\+\\\\\\.(js\\|ts\\)\\$'