From dae3556ccd014df8711e6ca1dd23545b5fd3dccf Mon Sep 17 00:00:00 2001 From: ssylvia Date: Thu, 29 Aug 2024 17:00:33 -0400 Subject: [PATCH] Faster matching --- customDictionary.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/customDictionary.ts b/customDictionary.ts index 63535c6..dd83ee3 100644 --- a/customDictionary.ts +++ b/customDictionary.ts @@ -177,10 +177,17 @@ export function createCustomDictionarySettingsUI(containerEl: HTMLElement, plugi createDictionaryTableUI(customDictionaryContainer, plugin); } +// Escape special characters in a string to be used in a regular expression +function escapeRegExp(string: string): string { + return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + // Replace text with custom dictionary entries export function replaceTextWithCustomDictionary(text: string, customDictionary: CustomDictionarySettings['customDictionary']): string { - for (const entry of customDictionary) { - text = text.replace(new RegExp(entry.source, 'g'), entry.replace); - } - return text; + customDictionary.map(entry => escapeRegExp(entry.source)).join('|'); + + return text.replace(new RegExp(customDictionary.map(entry => escapeRegExp(entry.source)).join('|'), 'g'), (match) => { + const entry = customDictionary.find(entry => new RegExp(escapeRegExp(entry.source)).test(match)); + return entry ? entry.replace : match; + }); }