Skip to content

Commit ef5a0bd

Browse files
committed
vendor regex-escaping code
1 parent f3bce8c commit ef5a0bd

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

packages/utils/src/string.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,3 +101,20 @@ export function isMatchingPattern(value: string, pattern: RegExp | string): bool
101101
}
102102
return false;
103103
}
104+
105+
/**
106+
* Given a string, escape characters which have meaning in the regex grammar, such that the result is safe to feed to
107+
* `new RegExp()`.
108+
*
109+
* Based on https://github.com/sindresorhus/escape-string-regexp. Vendored to a) reduce the size by skipping the runtime
110+
* type-checking, and b) ensure it gets down-compiled for old versions of Node (the published package only supports Node
111+
* 12+).
112+
*
113+
* @param regexString The string to escape
114+
* @returns An version of the string with all special regex characters escaped
115+
*/
116+
export function escapeStringForRegex(regexString: string): string {
117+
// escape the hyphen separately so we can also replace it with a unicode literal hyphen, to avoid the problems
118+
// discussed in https://github.com/sindresorhus/escape-string-regexp/issues/20.
119+
return regexString.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d');
120+
}

0 commit comments

Comments
 (0)