skip to Main Content

I’m trying to remove all HTML elements from an article and adding a highlight class at the end to highlight the search word. Unfortunately, this regex doesn’t seem to work as expected. According to this post, a dynamic regex should be passed as a new RegExp().

const article = "some article content";

const format = (query, data) => {
    // remove all html elements
    const output =
      data.replace(/<[^>]*>?/gi, "").length > 400
        ? data.replace(/<[^>]*>?/gi, "").slice(0, 400) + "..."
        : data.replace(/<[^>]*>?/gi, "");

        //regex
    const highlight = new RegExp(String.raw`/${query}/`, "gi");

    // add highlight 
    return output.replace(
      highlight,
      `<span className="highlight">${query}</span>`
    );
  };

HTML:

<p className="paragraph--s">{format(searchTag, article)}</p>

2

Answers


  1. Chosen as BEST ANSWER

    This function works without a loop. The key was to remove the backslashes from the regex and save each step in a separate variable.

    const highlight = (search, data) => {
    if (!search) return data;
    
    const regex = new RegExp(String.raw`${search}`, "gi");
    
    const output = data.replace(regex, `<span className="highlight">$&</span>`);
    
    return output;
    };
    

  2. The function takes two parameters: text, which is the text you want to search, and words, an array of words you want to highlight. It can handle multiple words in the text.

    function highlightWords(text, words) {
        let output = text;
        words.forEach(word => {
            const regex = new RegExp(word, 'gi');
            output = output.replace(regex, '<strong>$&</strong>');
        });
        output = output.substring(0, 300); // Limit output to 300 characters, if needed
        return output;
    }
    
    function highlightText() {
        const text = document.getElementById('text').value;
        const searchWordsInput = document.getElementById('searchWords').value;
        const searchWords = searchWordsInput.split(',').map(word => word.trim());
    
        const highlightedText = highlightWords(text, searchWords);
        document.getElementById('result').innerHTML = highlightedText;
    }
    strong {
        background-color: yellow;
    }
    #result {
        margin-top: 20px;
        font-size: 16px;
        line-height: 1.5;
    }
    <label for="text">Text to Search:</label><br />
    <textarea id="text" rows="5" cols="50">The quick brown fox jumps over the lazy dog.</textarea>
    <br>
    <label for="searchWords">Words to Highlight (comma-separated):</label><br />
    <input type="text" id="searchWords" value="fox, dog" placeholder="Enter words to highlight">
    <br><br />
    <button onclick="highlightText()">Highlight Words</button>
    
    <span id="result"></span>

    I originally posted PHP code not realizing you needed JavaScript. Here’s translation.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search