Skip to content

Commit

Permalink
fix: fixes crash when highlighting strings with special characters
Browse files Browse the repository at this point in the history
  • Loading branch information
micheleriva committed Jan 22, 2024
1 parent e9dff34 commit a78186c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
12 changes: 12 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,15 @@ describe('trim method', () => {
assert.strictEqual(highlighter.highlight(text, 'the').trim(5, false), '<mark class="orama-highlight">The</mark> q')
})
})

describe('special characters', () => {
it('should correctly highlight a text with special characters', () => {
const text = 'C++ is a hell of a language'
const searchTerm = 'C++'
const expectedResult = '<mark class="orama-highlight">C++</mark> is a hell of a language'

const highlighter = new Highlight()

assert.strictEqual(highlighter.highlight(text, searchTerm).HTML, expectedResult)
})
})
6 changes: 5 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export class Highlight {
const CSSClass = this.options.CSSClass ?? defaultOptions.CSSClass
const regexFlags = caseSensitive ? 'g' : 'gi'
const boundary = wholeWords ? '\\b' : ''
const searchTerms = (caseSensitive ? searchTerm : searchTerm.toLowerCase()).trim().split(/\s+/).join('|')
const searchTerms = this.escapeRegExp(caseSensitive ? searchTerm : searchTerm.toLowerCase()).trim().split(/\s+/).join('|')
const regex = new RegExp(`${boundary}${searchTerms}${boundary}`, regexFlags)
const positions: Array<{ start: number, end: number }> = []
const highlightedParts: string[] = []
Expand Down Expand Up @@ -91,4 +91,8 @@ export class Highlight {
get HTML (): string {
return this._HTML
}

private escapeRegExp(string: string): string {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
}

0 comments on commit a78186c

Please sign in to comment.