Home > OS >  Highlight partial matches from array of strings - JavaScript
Highlight partial matches from array of strings - JavaScript

Time:05-11

I'm creating a small project which will go through the contents of a textarea element, find words from the banned words list and highlight them if they are found. I've implemented a solution which works for full words, however in the scenario of edge cases, I've run into quite the pickle. Below is the code from the project:

const bannedWords = ['treatment', 'cancer', 'allergens'];
document.addEventListener('DOMContentLoaded', () => {
    let checkButton = document.querySelector('.check__btn');
    let textArea = document.querySelector('textarea');

    checkButton.addEventListener('click', (e) => {
        e.preventDefault();
        let inputString = textArea.value.split(" ");
        for (let i = 0; i < inputString.length; i  ) {

            if (bannedWords.includes(inputString[i])) {
                inputString[i] = `<mark>${inputString[i]}</mark>`;
            }
        }
        let outputText = document.querySelector('.output__text');
        outputText.innerHTML = inputString.join(" ");

        return false;
    });
});

So for example, if a user was to input 'treat' or 'cancerous' for example, they won't be highlighted since they technically don't appear in the list.

Any help with this would be appreciated! Cheers.

CodePudding user response:

I think your problem is quite similar to what vscode files search does. When you hit Ctrl P and enter some file name for eg: "numbrepinut" it would still show you the file named numberInput.js considering it a similar result. Please check the following links:

  1. Which algorithm is used to implement search for files in Visual Studio Code / Google Chrome Developer / Sublime (Ctrl p or Cmd p)?
  2. https://levelup.gitconnected.com/fuzzy-searches-in-vs-code-tips-to-increase-developer-focus-and-productivity-6809c0f3ce9a

CodePudding user response:

You can try below snipped and improve.

I suggest you instead of textarea prefer contenteditable div so curse word can be put into span or any inline block element and that can be inserted into that div. textarea dont give that freedom.

const bannedWords = ['exercitation', 'dolore', 'cupidatat'];
document.addEventListener('DOMContentLoaded', () => {
    let checkButton = document.querySelector('#check__btn');
    let textArea = document.querySelector('div');

    checkButton.addEventListener('click', (e) => {
        e.preventDefault();
        let tempInnerText = textArea.innerText;
        bannedWords.forEach(word => {
            tempInnerText = tempInnerText.replaceAll(word, `<span class='banned_word'>${word}</span>`)
        });
        textArea.innerHTML = tempInnerText;
    });
});
.banned_word {
    background-color: red;
    color: #fff;
}
<div contenteditable>
    Lorem ipsum <span>dolor</span> sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore
    et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
    commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
    pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est
    laborum.
</div>
<button id='check__btn'>Check</button>

To get text content from div you can use innerText property, it will return plain text content from that div without any html element.
  • Related