-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
Copy pathmatch-query.js
40 lines (34 loc) · 1.03 KB
/
match-query.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import get from 'lodash/get'
export default (query, page, additionalStr = null) => {
let domain = get(page, 'title', '')
if (get(page, 'frontmatter.tags')) {
domain += ` ${page.frontmatter.tags.join(' ')}`
}
if (additionalStr) {
domain += ` ${additionalStr}`
}
return matchTest(query, domain)
}
const matchTest = (query, domain) => {
const escapeRegExp = str => str.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
const words = query
.split(/\s+/g)
.map(str => str.trim())
.filter(str => !!str)
const hasTrailingSpace = query.endsWith(' ')
const searchRegex = new RegExp(
words
.map((word, index) => {
if (words.length === index + 1 && !hasTrailingSpace) {
// The last word - ok with the word being "startswith"-like
return `(?=.*${escapeRegExp(word)})`
} else {
// Not the last word - expect the whole word exactly
return `(?=.*${escapeRegExp(word)}.*)`
}
})
.join('') + '.+',
'gi'
)
return searchRegex.test(domain)
}