add word boundaries to terms, escape regex chars

This commit is contained in:
Fraser
2023-08-15 22:39:08 -04:00
parent 4fcc46dac1
commit 5e4198aef9
+5 -2
View File
@@ -15,8 +15,11 @@ const MyApp: AppType = ({ Component, pageProps }) => {
.then((res) => res.json())
.then((data) => {
const glossary: Glossary = new Map(Object.entries(data));
const keys = Array.from(glossary.keys()).sort((a, b) => b.length - a.length);
console.log(keys);
const keys = Array.from(glossary.keys())
.sort((a, b) => b.length - a.length) // sort by length descending
.map((k) => k.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')) // escape regex chars
.map((k) => `\\b${k}\\b`); // add word boundaries
const regex = new RegExp(keys.join("|"), "gim");
setGlossary({ g: glossary, r: regex });
});