Skip to content

Commit

Permalink
fix(#1574): Search highlighting breaks for a single dot
Browse files Browse the repository at this point in the history
see #1574
  • Loading branch information
leiyre committed Jun 29, 2022
1 parent 2f54f5b commit 1d9b3f3
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions frontend/plugins/highlight-search.js
Expand Up @@ -22,8 +22,7 @@ export default (context, inject) => {
.replace(/&/g, "&")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
.replace(/"/g, "&quot;");
};

function htmlHighlightText(text) {
Expand All @@ -35,6 +34,10 @@ export default (context, inject) => {
return new RegExp(q, "gi");
};

const escapeRegExp = function (text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};

const highlightSearch = function (query, text) {
const escapedText = htmlText(text);
if (!query) {
Expand All @@ -53,7 +56,10 @@ export default (context, inject) => {
);
text = htmlText(text);
sortedKeywords.forEach((keyword) => {
const regex = new RegExp(`([^a-zA-ZÀ-ÿ\u00f1\u00d1]|^)${keyword}`, "gmi");
const regex = new RegExp(
`([^a-zA-ZÀ-ÿ\u00f1\u00d1]|^)${escapeRegExp(keyword)}`,
"gmi"
);
text = text.replace(regex, (match) => htmlHighlightText(match));
});

Expand All @@ -62,7 +68,10 @@ export default (context, inject) => {

const keywordsSpans = function (text, keywords) {
return (keywords || []).flatMap((keyword) => {
const regex = new RegExp(`([^a-zA-ZÀ-ÿ\u00f1\u00d1]|^)${keyword}`, "gmi");
const regex = new RegExp(
`([^a-zA-ZÀ-ÿ\u00f1\u00d1]|^)${escapeRegExp(keyword)}`,
"gmi"
);
return [...text.matchAll(regex)].map((match) => {
return {
start: match.index,
Expand Down

0 comments on commit 1d9b3f3

Please sign in to comment.