From 266c807ff5c80ae39e0844f6e4f2796a2d4dbe0d Mon Sep 17 00:00:00 2001 From: Sara Vieira Date: Mon, 25 Mar 2024 15:46:50 +0000 Subject: [PATCH] fix - should not break when search is null --- src/index.test.ts | 11 ++++++++++- src/index.ts | 4 ++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/index.test.ts b/src/index.test.ts index 3d12b49..73960ba 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -205,12 +205,21 @@ describe("special characters", () => { }); describe("empty example", () => { + // even though it is not expected we should make sure it won't break it("should not break when text is null", () => { const searchTerm = "C"; const highlighter = new Highlight(); - // even though it is not expected we should make sure it won't break // @ts-expect-error assert.strictEqual(highlighter.highlight(null, searchTerm).HTML, ""); }); + it("should not break when search term is null", () => { + const highlighter = new Highlight(); + + assert.strictEqual( + // @ts-expect-error + highlighter.highlight(null, null).HTML, + '' + ); + }); }); diff --git a/src/index.ts b/src/index.ts index dbcd63d..0cd1a97 100644 --- a/src/index.ts +++ b/src/index.ts @@ -27,7 +27,7 @@ export class Highlight { } public highlight(text: string, searchTerm: string): Highlight { - this._searchTerm = searchTerm; + this._searchTerm = searchTerm ?? ""; this._originalText = text ?? ""; const caseSensitive = @@ -38,7 +38,7 @@ export class Highlight { const regexFlags = caseSensitive ? "g" : "gi"; const boundary = wholeWords ? "\\b" : ""; const searchTerms = this.escapeRegExp( - caseSensitive ? searchTerm : searchTerm.toLowerCase() + caseSensitive ? this._searchTerm : this._searchTerm.toLowerCase() ) .trim() .split(/\s+/)