Skip to content

Commit f00836b

Browse files
committed
feat(internal): escapeRegExp
Signed-off-by: Lexus Drumgold <unicornware@flexdevelopment.llc>
1 parent 7bc8031 commit f00836b

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/**
2+
* @file Unit Tests - escapeRegExp
3+
* @module mlly/internal/tests/unit/escapeRegExp
4+
*/
5+
6+
import testSubject from '../escape-reg-exp'
7+
8+
describe('unit:internal/escapeRegExp', () => {
9+
it('should escape special characters', () => {
10+
// Arrange
11+
const pattern: string = '\\ ^ $ * + ? . ( ) | { } [ ] -'
12+
const expected: string =
13+
'\\\\ \\^ \\$ \\* \\+ \\? \\. \\( \\) \\| \\{ \\} \\[ \\] \\x2d'
14+
15+
// Act + Expect
16+
expect(testSubject(pattern)).to.equal(expected)
17+
})
18+
})

src/internal/escape-reg-exp.ts

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* @file Internal - escapeRegExp
3+
* @module mlly/internal/escapeRegExp
4+
*/
5+
6+
import type { NodeError } from '@flex-development/errnode'
7+
import validateString from './validate-string'
8+
9+
/**
10+
* Escapes special characters in the given regex `pattern`.
11+
*
12+
* A backslash escape (`\\`) is used when valid. A `\x2d` escape is used when
13+
* the former would be disallowed by stricter Unicode pattern grammar.
14+
*
15+
* @param {string} pattern - Regex pattern to escape
16+
* @return {string} `pattern` with special characters escaped
17+
* @throws {NodeError<TypeError>} If `pattern` is not a string
18+
*/
19+
const escapeRegExp = (pattern: string): string => {
20+
validateString(pattern, 'pattern')
21+
return pattern.replace(/[$()*+.?[\\\]^{|}]/g, '\\$&').replace(/-/g, '\\x2d')
22+
}
23+
24+
export default escapeRegExp

0 commit comments

Comments
 (0)