fix(search): escape special characters for search, fixed #369

This commit is contained in:
qingwei.li 2018-02-10 12:48:18 +08:00 • committed by cinwell.li
commit 9755439670

View file

@ -7,7 +7,7 @@ function escapeHtml (string) {
'<': '&lt;', '<': '&lt;',
'>': '&gt;', '>': '&gt;',
'"': '&quot;', '"': '&quot;',
'\'': '&#39;', "'": '&#39;',
'/': '&#x2F;' '/': '&#x2F;'
} }
@ -17,18 +17,19 @@ function escapeHtml (string) {
function getAllPaths (router) { function getAllPaths (router) {
const paths = [] const paths = []
helper.dom.findAll('a:not([data-nosearch])') helper.dom.findAll('a:not([data-nosearch])').map(node => {
.map(node => { const href = node.href
const href = node.href const originHref = node.getAttribute('href')
const originHref = node.getAttribute('href') const path = router.parse(href).path
const path = router.parse(href).path
if (path && if (
paths.indexOf(path) === -1 && path &&
!Docsify.util.isAbsolutePath(originHref)) { paths.indexOf(path) === -1 &&
paths.push(path) !Docsify.util.isAbsolutePath(originHref)
} ) {
}) paths.push(path)
}
})
return paths return paths
} }
@ -92,7 +93,11 @@ export function search (query) {
if (postTitle && postContent) { if (postTitle && postContent) {
keywords.forEach((keyword, i) => { 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 indexTitle = -1
let indexContent = -1 let indexContent = -1
@ -113,11 +118,12 @@ export function search (query) {
if (end > postContent.length) end = postContent.length if (end > postContent.length) end = postContent.length
const matchContent = '...' + const matchContent =
'...' +
escapeHtml(postContent) escapeHtml(postContent)
.substring(start, end) .substring(start, end)
.replace(regEx, `<em class="search-keyword">${keyword}</em>`) + .replace(regEx, `<em class="search-keyword">${keyword}</em>`) +
'...' '...'
resultStr += matchContent resultStr += matchContent
} }
@ -159,12 +165,9 @@ export function init (config, vm) {
paths.forEach(path => { paths.forEach(path => {
if (INDEXS[path]) return count++ if (INDEXS[path]) return count++
helper helper.get(vm.router.getFile(path)).then(result => {
.get(vm.router.getFile(path)) INDEXS[path] = genIndex(path, result, vm.router, config.depth)
.then(result => { len === ++count && saveData(config.maxAge)
INDEXS[path] = genIndex(path, result, vm.router, config.depth) })
len === ++count && saveData(config.maxAge)
})
}) })
} }