From bb2065cf07979f85f3a01eab5f5d441754858216 Mon Sep 17 00:00:00 2001 From: KoloMl Date: Fri, 3 Jan 2025 03:42:03 +0400 Subject: [PATCH] Added escaping utility function for RegExp --- src/lib/utils.js | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/lib/utils.js b/src/lib/utils.js index db17ea5..c7a6531 100644 --- a/src/lib/utils.js +++ b/src/lib/utils.js @@ -21,3 +21,23 @@ export function findDeepObject(targetObject, path) { return result; } + +/** + * Matches all the characters needing replacement. + * + * Gathered from right here: https://stackoverflow.com/a/3561711/16048617. Because I don't want to introduce some + * library for that. + * + * @type {RegExp} + */ +const unsafeRegExpCharacters = /[/\-\\^$*+?.()|[\]{}]/g; + +/** + * Escape all the RegExp syntax-related characters in the following value. + * @param {string} value Original value. + * @return {string} Resulting value with all needed characters escaped. + */ +export function escapeRegExp(value) { + unsafeRegExpCharacters.lastIndex = 0; + return value.replace(unsafeRegExpCharacters, "\\$&"); +}