Skip to content

Commit 9987e5e

Browse files
committed
fix(search): escape special characters for search, fixed #369
1 parent 21dd481 commit 9987e5e

File tree

1 file changed

+26
-23
lines changed

1 file changed

+26
-23
lines changed

src/plugins/search/search.js

+26-23
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ function escapeHtml (string) {
77
'<': '&lt;',
88
'>': '&gt;',
99
'"': '&quot;',
10-
'\'': '&#39;',
10+
"'": '&#39;',
1111
'/': '&#x2F;'
1212
}
1313

@@ -17,18 +17,19 @@ function escapeHtml (string) {
1717
function getAllPaths (router) {
1818
const paths = []
1919

20-
helper.dom.findAll('a:not([data-nosearch])')
21-
.map(node => {
22-
const href = node.href
23-
const originHref = node.getAttribute('href')
24-
const path = router.parse(href).path
25-
26-
if (path &&
27-
paths.indexOf(path) === -1 &&
28-
!Docsify.util.isAbsolutePath(originHref)) {
29-
paths.push(path)
30-
}
31-
})
20+
helper.dom.findAll('a:not([data-nosearch])').map(node => {
21+
const href = node.href
22+
const originHref = node.getAttribute('href')
23+
const path = router.parse(href).path
24+
25+
if (
26+
path &&
27+
paths.indexOf(path) === -1 &&
28+
!Docsify.util.isAbsolutePath(originHref)
29+
) {
30+
paths.push(path)
31+
}
32+
})
3233

3334
return paths
3435
}
@@ -92,7 +93,11 @@ export function search (query) {
9293

9394
if (postTitle && postContent) {
9495
keywords.forEach((keyword, i) => {
95-
const regEx = new RegExp(keyword, 'gi')
96+
// From https://github.com/sindresorhus/escape-string-regexp
97+
const regEx = new RegExp(
98+
keyword.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&'),
99+
'gi'
100+
)
96101
let indexTitle = -1
97102
let indexContent = -1
98103

@@ -113,11 +118,12 @@ export function search (query) {
113118

114119
if (end > postContent.length) end = postContent.length
115120

116-
const matchContent = '...' +
121+
const matchContent =
122+
'...' +
117123
escapeHtml(postContent)
118124
.substring(start, end)
119125
.replace(regEx, `<em class="search-keyword">${keyword}</em>`) +
120-
'...'
126+
'...'
121127

122128
resultStr += matchContent
123129
}
@@ -159,12 +165,9 @@ export function init (config, vm) {
159165
paths.forEach(path => {
160166
if (INDEXS[path]) return count++
161167

162-
helper
163-
.get(vm.router.getFile(path))
164-
.then(result => {
165-
INDEXS[path] = genIndex(path, result, vm.router, config.depth)
166-
len === ++count && saveData(config.maxAge)
167-
})
168+
helper.get(vm.router.getFile(path)).then(result => {
169+
INDEXS[path] = genIndex(path, result, vm.router, config.depth)
170+
len === ++count && saveData(config.maxAge)
171+
})
168172
})
169173
}
170-

0 commit comments

Comments
 (0)