Skip to content

Commit

Permalink
fix(search): escape special characters for search, fixed #369
Browse files Browse the repository at this point in the history
  • Loading branch information
QingWei-Li committed Feb 11, 2018
1 parent 761ccc2 commit 9755439
Showing 1 changed file with 26 additions and 23 deletions.
49 changes: 26 additions & 23 deletions src/plugins/search/search.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ function escapeHtml (string) {
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
'\'': '&#39;',
"'": '&#39;',
'/': '&#x2F;'
}

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

helper.dom.findAll('a:not([data-nosearch])')
.map(node => {
const href = node.href
const originHref = node.getAttribute('href')
const path = router.parse(href).path

if (path &&
paths.indexOf(path) === -1 &&
!Docsify.util.isAbsolutePath(originHref)) {
paths.push(path)
}
})
helper.dom.findAll('a:not([data-nosearch])').map(node => {
const href = node.href
const originHref = node.getAttribute('href')
const path = router.parse(href).path

if (
path &&
paths.indexOf(path) === -1 &&
!Docsify.util.isAbsolutePath(originHref)
) {
paths.push(path)
}
})

return paths
}
Expand Down Expand Up @@ -92,7 +93,11 @@ export function search (query) {

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

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

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

const matchContent = '...' +
const matchContent =
'...' +
escapeHtml(postContent)
.substring(start, end)
.replace(regEx, `<em class="search-keyword">${keyword}</em>`) +
'...'
'...'

resultStr += matchContent
}
Expand Down Expand Up @@ -159,12 +165,9 @@ export function init (config, vm) {
paths.forEach(path => {
if (INDEXS[path]) return count++

helper
.get(vm.router.getFile(path))
.then(result => {
INDEXS[path] = genIndex(path, result, vm.router, config.depth)
len === ++count && saveData(config.maxAge)
})
helper.get(vm.router.getFile(path)).then(result => {
INDEXS[path] = genIndex(path, result, vm.router, config.depth)
len === ++count && saveData(config.maxAge)
})
})
}

0 comments on commit 9755439

Please sign in to comment.