Added escaping utility function for RegExp

This commit is contained in:
koloml committed 2025-01-03 03:42:03 +04:00
1 parent 62bcba34da
commit bb2065cf07
1 file changed
+20
+20
View File
@@ -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, "\\$&");
}