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,15 +17,16 @@ 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 (
path &&
paths.indexOf(path) === -1 && paths.indexOf(path) === -1 &&
!Docsify.util.isAbsolutePath(originHref)) { !Docsify.util.isAbsolutePath(originHref)
) {
paths.push(path) paths.push(path)
} }
}) })
@ -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,7 +118,8 @@ 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>`) +
@ -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))
.then(result => {
INDEXS[path] = genIndex(path, result, vm.router, config.depth) INDEXS[path] = genIndex(path, result, vm.router, config.depth)
len === ++count && saveData(config.maxAge) len === ++count && saveData(config.maxAge)
}) })
}) })
} }