Skip to content

Commit 3fa6727

Browse files
committed
Add helper method to escape special glob characters
Signed-off-by: Kyle Harding <[email protected]>
1 parent a57bd91 commit 3fa6727

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

lib/glob.js

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,20 @@ class Glob {
44

55
// If not a glob pattern then just match the string.
66
if (!this.glob.includes('*')) {
7-
this.regexp = new RegExp(`.*${this.glob}.*`, 'u')
7+
// Escape special regex characters for non-glob patterns
8+
const escapedGlob = this.escapeRegExp(this.glob)
9+
this.regexp = new RegExp(`.*${escapedGlob}.*`, 'u')
810
return
911
}
1012
this.regexptText = this.globize(this.glob)
1113
this.regexp = new RegExp(`^${this.regexptText}$`, 'u')
1214
}
1315

16+
// Helper method to escape special regex characters
17+
escapeRegExp (string) {
18+
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') // $& means the whole matched string
19+
}
20+
1421
globize (glob) {
1522
return glob
1623
.replace(/\\/g, '\\\\') // escape backslashes
@@ -41,4 +48,4 @@ class Glob {
4148
return s.replaceAll(this.regexp, replacement)
4249
}
4350
}
44-
module.exports = Glob
51+
module.exports = Glob

0 commit comments

Comments
 (0)