Skip to content

Commit 4bb0022

Browse files
committed
Refactor regexp generators into shared module
1 parent 9fa322b commit 4bb0022

File tree

4 files changed

+22
-13
lines changed

4 files changed

+22
-13
lines changed

lib/ReactTags.js

+3-6
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import PropTypes from 'prop-types'
33
import Tag from './Tag'
44
import Input from './Input'
55
import Suggestions from './Suggestions'
6-
import { escapeForRegExp } from './utils'
6+
import { matchExact, matchPartial } from './concerns/matchers'
77

88
const KEYS = {
99
ENTER: 'Enter',
@@ -34,10 +34,7 @@ function pressDelimiterKey (e) {
3434
if (this.state.query.length >= this.props.minQueryLength) {
3535
// Check if the user typed in an existing suggestion.
3636
const match = this.state.options.findIndex((option) => {
37-
const query = escapeForRegExp(this.state.query)
38-
const regex = new RegExp(`^${query}$`, 'i')
39-
40-
return regex.test(option.name)
37+
return matchExact(this.state.query).test(option.name)
4138
})
4239

4340
const index = this.state.selected === -1 ? match : this.state.selected
@@ -80,7 +77,7 @@ function pressBackspaceKey () {
8077
}
8178

8279
function filterSuggestions (query, suggestions) {
83-
const regexp = new RegExp(`(?:^|\\s)${escapeForRegExp(query)}`, 'i')
80+
const regexp = matchPartial(query)
8481
return suggestions.filter((item) => regexp.test(item.name))
8582
}
8683

lib/Suggestions.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import React from 'react'
2-
import { escapeForRegExp } from './utils'
2+
import { matchAny } from './concerns/matchers'
33

44
function markIt (name, query) {
5-
const regexp = new RegExp(escapeForRegExp(query), 'gi')
5+
const regexp = matchAny(query)
66
return name.replace(regexp, '<mark>$&</mark>')
77
}
88

lib/concerns/matchers.js

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
function escapeForRegExp (string) {
2+
return string.replace(/[-\\^$*+?.()|[\]{}]/g, '\\$&')
3+
}
4+
5+
function matchAny (string) {
6+
return new RegExp(escapeForRegExp(string), 'gi')
7+
}
8+
9+
function matchPartial (string) {
10+
return new RegExp(`(?:^|\\s)${escapeForRegExp(string)}`, 'i')
11+
}
12+
13+
function matchExact (string) {
14+
return new RegExp(`^${escapeForRegExp(string)}$`, 'i')
15+
}
16+
17+
module.exports = { escapeForRegExp, matchAny, matchPartial, matchExact }

lib/utils.js

-5
This file was deleted.

0 commit comments

Comments
 (0)