From 9987e5ee25d2aba451f739463bf4516fb4f3eee1 Mon Sep 17 00:00:00 2001 From: "qingwei.li" Date: Sat, 10 Feb 2018 12:48:18 +0800 Subject: [PATCH] fix(search): escape special characters for search, fixed #369 --- src/plugins/search/search.js | 49 +++++++++++++++++++----------------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/src/plugins/search/search.js b/src/plugins/search/search.js index 7ecf21a62..4c73e2def 100644 --- a/src/plugins/search/search.js +++ b/src/plugins/search/search.js @@ -7,7 +7,7 @@ function escapeHtml (string) { '<': '<', '>': '>', '"': '"', - '\'': ''', + "'": ''', '/': '/' } @@ -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 } @@ -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 @@ -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, `${keyword}`) + - '...' + '...' resultStr += matchContent } @@ -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) + }) }) } -